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;
}
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 found this code online on tutorials point. link https://www.tutorialspoint.com/cplusplus-program-to-generate-all-possible-combinations-out-of-a-b-c-d-e.
I tried to think of how to modify it so that it would randomly a single combination from the generated list, but I'm haven't figured it out yet.
#include<iostream>
using namespace std;
void Combi(char a[], int reqLen, int s, int currLen, bool check[], int l)
{
if(currLen > reqLen)
return;
else if (currLen == reqLen) {
cout<<"\t";
for (int i = 0; i < l; i++) {
if (check[i] == true) {
cout<<a[i]<<" ";
}
}
cout<<"\n";
return;
}
if (s == l) {
return;
}
check[s] = true;
Combi(a, reqLen, s + 1, currLen + 1, check, l);
check[s] = false;
Combi(a, reqLen, s + 1, currLen, check, l);
}
int main() {
int i,n;
bool check[n];
cout<<"Enter the number of element array have: ";
cin>>n;
char a[n];
cout<<"\n";
for(i = 0; i < n; i++) {
cout<<"Enter "<<i+1<<" element: ";
cin>>a[i];
check[i] = false;
}
for(i = 1; i <= n; i++) {
cout<<"\nThe all possible combination of length "<<i<<" for the given array set:\n";
Combi(a, i, 0, 0, check, n);
}
return 0;
}
im not a c++ specialist, but i think you should add a random number from -ArrayLenght to ArrayLenght, at least this works in python(which is written in c++)
i hope i understood your question right
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.
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 << " ";
}
}
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;
}