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;
}
Related
There is a given pseudo code.
int Function(X : array[P..Q] of integer)
1 maxSoFar = 0
2 for L = P to Q
I was using C and trying to change it into C++ code.
The reason that I am struggling with it is I have no idea how to express it is start from 'P' in the loop.
I do not know how to do that before initilization even without parameter.
int Function(vector<int> X)
{
int maxSoFar = 0;
for (int I = 0; I < X.size(); I++) ;
}
This is what I did.
I wonder if it is same with the pseudo code or not.
You can just divide your vector size by 2:
#include <vector>
#include <iostream>
using namespace std;
int f(vector<int> v) {
int maxSoFar = 0;
int len = v.size();
for (int i = len / 2; i < len; i++) { // i = len / 2, starts from the middle
maxSoFar += v[i];
cout << v[i] << ' ';
cout << maxSoFar << endl;
}
}
int main(void) {
vector<int> v = {1, 3, 5};
f(v);
}
output:
3 3
5 8
You should take a closer look at the for loop on wikipedia: for (initialization; break condition; incrementation)
#include<iostream>
using namespace std;
int main()
{
int i,n;
cout<<"enter the number of elements : ";
cin>>n;
int a[n];
cout<<endl<<"enter the value of this array : ";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<endl<<"print the last half elements of this array : ";
for(i=(n/2);i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
I have a small program to sort random numbers into the right sequence number. Well, I want to see every random number move. what should be added to it?
#include <iostream>
using namespace std;
void pindah (int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void tukar (int arr[], int n) {
int i, j;
bool trade;
for (i=0; i < n-1; i++) {
trade = false;
for (j=0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
pindah(&arr[j], &arr[j+1]);
trade = true;
}
}
if (trade == false)
break;
}
}
void cetakArray (int arr[], int n) {
int i;
for (i=0; i<n; i++) {
cout << arr[i] << " "; //tampil data
}
}
int main () {
int arr[] = {4, 6, 7, 2, 1, 5, 8, 10, 9, 3};
int n = sizeof(arr) / sizeof(int); //menghitung jumlah data array
cout << "setelah diurutkan : \n";
tukar (arr, n);
cetakArray (arr, n);
}
please help me
Assuming that by "into the right sequence" you mean from small to large, and assuming that you are willing to use C++11, we can easily obtain this with a lambda function. See the following example.
#include <vector>
#include <algorithm>
std::vector<int> values({4, 6, 7, 2, 1, 5, 8, 10, 9, 3});
int number_of_moves = 0;
std::sort(begin(values), end(values), [&](int lhs, int rhs)
{
if (lhs > rhs)
return false;
++number_of_moves;
std::cout << "I am going to swap " << lhs << " with " << rhs << '\n';
return true;
});
std::cout << "I took me " << number_of_moves << " move(s) to sort the vector\n";
Note: it is not clear to me what you mean by "movements in c++ boolean", so I chose to print the numbers that are going to be swapped.
EDIT: based on the comments I guess you want to count the number of movements, so I have added a counter. Note that a bool can only be true/false and cannot be used for counting.
The idea of the program is to input elements in an array. Then give the integer 'x' a value. If 'x' is 3 and the array a[] holds the elements {1,2,3,4,5,6}, we must "split" a[] into two other arrays. Lets say b[] and c[].
In b[] we must put all values lower or equal to 3 and in c[] all values greater than 3.
My question is- How can i express the 3 elements in b[i]?
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6];
int c[6];
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[i] = a[i]; // if d is 3, then i have 3 elements. How can i express them?
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[i] = a[i];
}
}
for (int i = 0; i < 3; i++) {
cout << b[i];
}
cout << endl;
for (int i = 3; i < 6; i++) {
cout << c[i];
}
return 0;
}
I think all you're trying to do is have a way to determine how many int values you're copying from a[] to either b[] or c[]. To do that, introduce two more counters that start at zero and increment with each item copied to the associated array:
Something like this:
#include <iostream>
using namespace std;
int main()
{
int a[6];
int b[6], b_count=0; // see here
int c[6], c_count=0; // see here
int d;
for (int i = 0; i < 6; i++) {
cin >> a[i];
}
cin >> d;
for (int i = 0; i < 6; i++) {
if (d >= a[i]) {
b[b_count++] = a[i]; // see here
}
}
for (int i = 0; i < 6; i++) {
if (d< a[i]) {
c[c_count++] = a[i]; // see here
}
}
for (int i = 0; i < b_count; i++) { // see here
cout << b[i];
}
cout << endl;
for (int i = 3; i < c_count; i++) { // and finally here
cout << c[i];
}
return 0;
}
Now, if you want b[] or c[] to be dynamic in their space allocation, then dynamic-managed containers like st::vector<> would be useful, but I don't think that is required for this specific task. Your b[] and c[] are already large enough to hold all elements from a[] if needed.
WhozCraigs answer does a good job showing what you need to solve this using traditional arrays according to your tasks requirements.
I'd just like to show you how this can be done if you were allowed the full arsenal of the standard library. It is why people are calling for you to use std::vector. Things gets simpler that way.
#include <algorithm>
#include <iostream>
int main()
{
int a[6] = {1, 2, 3, 4, 5, 6 }; // Not using input for brevity.
int x = 3; // No input, for brevity
// Lets use the std:: instead of primitives
auto first_part = std::begin(a);
auto last = std::end(a);
auto comparison = [x](int e){ return e <= x; };
auto second_part = std::partition(first_part, last, comparison);
// Print the second part.
std::for_each(second_part, last, [](int e){ std::cout << e; });
// The first part is first_part -> second_part
}
The partition function does exactly what your problem is asking you to solve, but it does it inside of the array a. The returned value is the first element in the second part.
use std::vectors. do not use int[]s.
with int[]s (that are pre-c++11) you could, with a few heavy assumptions, find array length with sizeof(X)/sizeof(X[0]); This has, however, never been a good practice.
in the example you provided, probably you wanted to:
#define MAX_LEN 100
...
int main() {
int a[MAX_LEN];
int b[MAX_LEN];
int c[MAX_LEN];
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
and use n from there on (these are common practice in programming schools)
Consider a function that reads a vector of ints:
std::vector<int> readVector() {
int n;
std::cout << "how many elements do you want to read?" << std::endl;
std::cin >> n;
std::vector<int> ret;
for (int i=0; i<n; i++) {
std::cout << "please enter element " << (i+1) << std::endl;
int el;
std::cin >> el;
ret.push_back(el);
}
return ret;
}
you could use, in main, auto a = readVector(); auto b = readVector(); a.size() would be the length, and would allow to keep any number of ints
Here's an example of how you'll approach it once you've a little more experience.
Anything you don't understand in here is worth studying here:
#include <iostream>
#include <vector>
#include <utility>
std::vector<int> get_inputs(std::istream& is)
{
std::vector<int> result;
int i;
while(result.size() < 6 && is >> i) {
result.push_back(i);
}
return result;
}
std::pair<std::vector<int>, std::vector<int>>
split_vector(const std::vector<int>& src, int target)
{
auto it = std::find(src.begin(), src.end(), target);
if (it != src.end()) {
std::advance(it, 1);
}
return std::make_pair(std::vector<int>(src.begin(), it),
std::vector<int>(it, src.end()));
}
void print_vector(const std::vector<int>& vec)
{
auto sep = " ";
std::cout << "[";
for (auto i : vec) {
std::cout << sep << i;
sep = ", ";
}
std::cout << " ]" << std::endl;
}
int main()
{
auto initial_vector = get_inputs(std::cin);
int pivot;
if(std::cin >> pivot)
{
auto results = split_vector(initial_vector, pivot);
print_vector(results.first);
print_vector(results.second);
}
else
{
std::cerr << "not enough data";
return 1;
}
return 0;
}
example input:
1 2 3 4 5 6
3
expected output:
[ 1, 2, 3 ]
[ 4, 5, 6 ]
I've written this code to sort an array using selection sort, but it doesn't sort the array correctly.
#include <cstdlib>
#include <iostream>
using namespace std;
void selectionsort(int *b, int size)
{
int i, k, menor, posmenor;
for (i = 0; i < size - 1; i++)
{
posmenor = i;
menor = b[i];
for (k = i + 1; k < size; k++)
{
if (b[k] < menor)
{
menor = b[k];
posmenor = k;
}
}
b[posmenor] = b[i];
b[i] = menor;
}
}
int main()
{
typedef int myarray[size];
myarray b;
for (int i = 1; i <= size; i++)
{
cout << "Ingrese numero " << i << ": ";
cin >> b[i];
}
selectionsort(b, size);
for (int l = 1; l <= size; l++)
{
cout << b[l] << endl;
}
system("Pause");
return 0;
}
I can't find the error. I'm new to C++.
Thanks for help.
The selectionSort() function is fine. Array init and output is not. See below.
int main()
{
int size = 10; // for example
typedef int myarray[size];
myarray b;
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<"Ingrese numero "<<i<<": ";
cin>>b[i];
}
selectionsort(b,size);
for (int i=0;i<size;i++)
//------------^^--^
{
cout<<b[l]<<endl;
}
system("Pause");
return 0;
}
In C and C++, an array with n elements starts with the 0 index, and ends with the n-1 index. For your example, the starting index is 0 and ending index is 9. When you iterate like you do in your posted code, you check if the index variable is less than (or not equal to) the size of the array, i.e. size. Thus, on the last step of your iteration, you access b[size], accessing the location in memory next to the last element in the array, which is not guaranteed to contain anything meaningful (being uninitialized), hence the random numbers in your output.
You provided some sample input in the comments to your question.
I compiled and executed the following, which I believe accurately reproduces your shown code, and your sample input:
#include <iostream>
void selectionsort(int* b, int size)
{
int i, k, menor, posmenor;
for(i=0;i<size-1;i++)
{
posmenor=i;
menor=b[i];
for(k=i+1;k<size;k++)
{
if(b[k]<menor)
{
menor=b[k];
posmenor=k;
}
}
b[posmenor]=b[i];
b[i]=menor;
}
}
int main(int argc, char **argv)
{
int a[10] = {-3, 100, 200, 2, 3, 4, -4, -5, 6, 0};
selectionsort(a, 10);
for (auto v:a)
{
std::cout << v << ' ';
}
std::cout << std::endl;
}
The resulting output was as follows:
-5 -4 -3 0 2 3 4 6 100 200
These results look correct. I see nothing wrong with your code, and by using the sample input you posted, this confirms that.
As you can see, I want to find the location of an given array.
For example :
I have an array {5 , 2, 3, 1} (I want to decide how many guesses I want to guess)
Then the program will sort it {1, 2, 3, 5}
At last, I'll be given a chance to guess the number which I desired how many guess (example : I want 2 number guesses, they are 5 and 3. then the program will search for the number 5 and 3. The program will tell me the location in the sorted array. Then it is "3 found at 3, 5 found at 4"
However, I have my code stuck in the sorting
this is my code :
#include <iostream>
using namespace std;
int main(void)
{
int temp, i, j, n, list[100];
cin>>n;
for(i=0; i<n; i++)
{
cin>>list[i];
}
for(i=0; i<n-1; i++)
for(j=i+1; j<n; j++)
if(list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
for(i=0; i<n; i++)
cout<<" "<<list[i];
cout<<endl;
return 0;
}
And this link is the full question of my project :
http://uva.onlinejudge.org/external/104/p10474.pdf
There is no problem in your sort function , by the way you can solve original problem in O(nlogn) , yours is O(n^2)
code:
#include <iostream>
#include <algorithm>
using namespace std;
int binary_search(int A[], int key, int imin, int imax)
{
if (imax < imin)
return -1;
else
{
int imid = (imax + imin)/2;
if (A[imid] > key)
// key is in lower subset
return binary_search(A, key, imin, imid - 1);
else if (A[imid] < key)
// key is in upper subset
return binary_search(A, key, imid + 1, imax);
else
// key has been found
return imid;
}
}
int main() {
// your code goes here
int n,q;
while(1){
cin >> n>> q;
if(n==0)
break;
int* a = new int[n];
int i;
for(i=0;i<n;i++)
cin >> a[i];
sort(a,a+n);
while(q--){
int k;
cin >> k;
k=binary_search(a,k,0,n-1);
if(k==-1)
cout << "not found" << endl;
else
cout << "found at :" << k+1 << endl;
}
}
return 0;
}