I need to solve a c++ problem but something doesn't work and i don't know why.
N numbers are given, divided in k sequences. I need to find out which sequences are equal, knowing that k divides n.
is the problem with some values as an example:
Here is the problem with some values as an example. (it's in romanian)
I tried something like this:
#include <bits/stdc++.h>
using namespace std;
bool compare(int a[], int b[], int n)
{
for(int i=1;i<=n;i++)
if(a[i]!=b[i])
return false;
return true;
}
int main()
{
int n, k;
int i, j, secv;
cin>>n>>k;
int flag=1, v[n];
for(i=1;i<=n;i++)
cin>>v[i];
secv=n/k;
for(i=1;i<k && flag==1;i++)
for(j=i+1; j<=k && flag==1; j++)
if(compare(v+i*secv, v+j*secv, secv)==true)
{
cout<<i<<" "<<j;
flag=0;
}
if(flag==1) cout<<"NU";
return 0;
}
If your array is of size k and you are iterating the first element at index 1 then there are two problems:
Your array will only be able to save k-1 elements because in memory an array's first element is at index 0.
Some of the default array functions like begin and size will include 0 index so it might produce unexpected results.
How an array is saved in memeory
An array name is just a placeholder to the continuous memory reference. So if you's starting your array with 1 then you're skipping through the first index.
The best practice is to start an array with index 0.
Related
hi I'm trying to implement this double pivot function and then pass the found indices to the recursive quicksort function with three calls (arr, left, pivot_sx) / (arr, pivot_sx + 1, pivot_dx-1) / (arr, pivot_dx + 1, right). I know that the function is still incomplete and that I do not return the indexes most likely I will declare a pointer to which I will assign the value of the left index and the right index will simply return it with a return.
the code I wrote for now is this:
#include <iostream>
#include<time.h>
#include <utility>
using namespace std;
int double_partition(int a[],int left,int right){
if(a[left]>a[right]){std::swap(a[left],a[right]);}
int piv_sx=a[left];
int piv_dx=a[right];
int i_piv_sx=left;
int i_piv_dx=right;
int i=left+1;
int j=right-1;
while(i<=j){
if(a[i]<=piv_sx){
std::swap(a[i],a[i_piv_sx]);
i_piv_sx+=1;
}else if(a[i]>=piv_dx){
std::swap(a[i],a[i_piv_dx]);
i_piv_dx-=1;
}
i++;
}
return 0;
}
void printArray(int arr[], int size){
int i;
for (i=0; i < size; i++)
cout<<" "<<arr[i];
cout<<std::endl;
}
int main()
{
srand(time(NULL));
int n;
cout << "Enter the number of items:" << "\n";
cin >>n;
int *arr = new int(n);
for (int x = 0; x < n; x++) {
int num = rand() % 10000;
arr[x]=num;
}
printArray(arr,n);
double_partition(arr,0,n-1);
printArray(arr,n);
}
as we know the pivot on the left must be smaller than the one on the right so at the beginning I compare the two pivots and if the one on the left is greater then I make the exchange.
After doing this I save the values of the pivots in two variables which I will then need to make the various comparisons.
and then I do this while loop where I start i from left + 1 because I don't need to compare the first element because I already know the value since it corresponds to the left pivot so it would be a useless comparison same reasoning for j = right-1.
I do all the comparisons and in the end when I compile and run the code sometimes I find a correct result and sometimes I find an incorrect result.
Is there anything I'm not doing right? Could anyone help me?
I should find the array in the situation where the elements on the left are smaller than the left pivot, the elements in the center are greater than the left pivot but smaller than the right pivot and the elements on the right will be greater than the right pivot.
int *arr = new int(n); gives you 1 int, initialized with the value n.
You want int *arr = new int[n];, which gives you an array of n ints.
Also don't forget to delete the array with delete[] arr; when you do not need it anymore.
I have this function that should take a matrix, compare the diagonal elements of the matrix and find the smallest one.
Here it should compare y[0][1] and y[1][0].
#include <iostream>
int Min(int, int [][2]);
using namespace std;
int main() {
int min, y[2][2];
y[0][0]=5;
y[0][1]=4;
y[1][0]=-9;
y[1][1]=0;
min = Min(2, y);
cout<<min;
return 0;
}
int Min(int k, int x[][2]){
int min=x[0][0];
for(int i=0; i<k;i++){
if(x[i][i]<min){
min=x[i][i];
}
}
return min;
}
It always returns 0. Why?
Here it should compare y[0][1] and y[1][0].
Your function goes through the diagonal of the matrix, it hence checks y[0][0] and y[1][1]. They are 5 and 0. The result is zero, which is to be expected.
Here it should compare y[0][1] and y[1][0].
But that's not what you say here:
int min=x[0][0];
or here:
if(x[i][i]<min){
min=x[i][i];
}
Since i cannot be both 0 and 1 at the same time, this accesses x[0][0] and x[1][1].
And for those elements, 0 is the correct minimum.
As a side note, your Min function can only work with matrices of size 2, so the k parameter is unnecessary. Multi-dimensional arrays are annoying like that.
To iterate over all items instead of just [0][0] and [1][1] you need to do:
for(int i=0; i<k; i++)
{
for(int j=0; j<k; j++)
{
if(x[i][j]<min)
{
min=x[i][j];
}
}
}
int Min(int k,const int x[][2])
{
int min=x[0][0];
for(int i=0; i<k;i++)
{
for(int j=0;j<k;j++)
{
if(x[i][j]<min)
{
min=x[i][j];
}
}
}
Earlier it was always showing zero because it had a mess with the column index. Outer for loop iterates k-1 times with first iteration at i=0, and second at i=1 and during both iterations it assigns the same index to both row and column(i.e., x [0][0] and x[1][1]). Perhaps it must assign the index x[0][0], x[0][1], x[1][0], x[1][1]. Earlier, it had only two iterations(the outer for loop) but now it takes four iterations assigning the appropriate index to both column and rows the efficient number of times.
I have written some code to add all elements of an array and display the result, but it does not work right, what's possibly going wrong?
I tried it with 2-5 elements, but the only one giving correct result is the one with 2 elements.
#include <iostream>
using namespace std;
int main() {
int n, sum=0;
int arr[n]; \\no of array elements
cout<<"enter the number of array elements\n";
cin>>n;
cout<<"enter the array elements\n";
for(int i=0; i<n; i++)
{
cin>>arr[i]; \\got my array filled
}
cout<<"calculating the sum...\n";
for(int i=0; i<n; i++)
{
sum=arr[i]+arr[i-1];
}
cout<<"the answer is:\n"<<sum; \\i think the problem is in this loop
return 0;
}
for a 3 elements array, if the input is 1,2,3; then the result is 5. Probably the code is excluding the first element
problem 1:
int n, sum=0;
int arr[n]; //no of array elements
you want to initial array by n. But this n is undefined.
so, you can write it
int n, sum=0;
cout<<"enter the number of array elements\n";
cin>>n;
int arr[n]; //no of array elements
problem 2:
sum=arr[i]+arr[i-1];
in each iteration, you have added just current array value and the previous array value. Also your code want to access arr[-1] address. :D
so, you can write it
sum=arr[i]+sum;
in each iteration arr[i] add with the previous total sum.
The problem is in the for.
You are for some reason subtracting arr[i] and arr[i-1] and adding it to sum?
2 elements work because if you take i = 1, i - 1 = 0. So you are summing up arr[0] and arr[1] which are all elements of the array.
If you want to SUM ALL elements in the array just do sum += arr[i]; (in the adding for).
Also you are setting sum to arr[i]-arr[i-1] and not summing it up.
I have homework assignment to implement merge sort in C++ via recursion. I'm not really good at recursion and what follows is the code I implemented, but it gives a stackoverflow error.
Kindly tell me what I am doing wrong. EDITED VERSION
#include<iostream>
using namespace std;
void divide(int A[], int n);
void sort();
int main(){
int A[4]={2,3,0,5};
divide(A, 4);
for(int i =0 ;i<4;i++)
cout<<A[i]<<endl;
getchar();
}
void divide(int A[], int n){
if(n<=2 && n>=1){
for(int i=0; i<n; i++)
if(A[i]>A[i+1]){
int temp=A[i];
A[i]= A[i+1];
A[i+1]=temp;
}
}
else{
divide(A, n/2);
divide(A,(n/2)+1 );
}
}
In the code above, n is the number of elements to sort and A is the array I'm sorting.
Calling the below code with
divide(A, 1);
Should illustrate the problem
void divide(int A[], int n){
if(n==2){ // first time n==1 so no, further calls are n==0 so also no.
for(int i=0; i<2; i++)
if(A[i]>A[i+1]){
int temp=A[i];
A[i]= A[i+1];
}
} else{
divide(A, n/2); // for both n==1 and n== 0 => n==0, calls divide(A, 0)
divide(A,(n/2)+1 ); // calls divide(A, 1) always
}
}
So the program will forever call divide(A, 0) until you run out of memory.
To stop this eternal recursion you need a correct stop condition
if (n<=2) {
// correct code for swapping 1 or 2 elements
} else
You could also check for incorrect values of n, which is 0, negative and larger than length of A.
Lets say you have A[]= {1,2,3} so you call
divide(A, 3);
Now in the else part of the program you need to split up A in to parts, N/2 elements and the rest.
divide(A, n/2);
in our example this gives n/2 = 3/2 = 1 so
divide(A, 1);
and starting in the element just after the n/2'th element
divide(A+(n/2), n-(n/2));
the first element is at A[0], so the remaining start at A[1] and contains n-(n/2)=3-(3/2)=3-1=2 elements.
And now the first if, it looks like a bubble-sort, but fails as it address an element beyond the end of the array.
if(n<=2 && n>=1){
for(int i=0; i<n; i++)
if(A[i]>A[i+1]) {
A[i+1] is beyond the end of the array for i=1 and n=2, n=2 => 2 elements at address A[0] and A[1] so A[i+1]=A[2] which is not part of the array A with length 2.
for(int i=0; i<n-1; i++)
solves that and also takes care of the case with n=1, which means the array contains only one element, which by definition is already sorted.
Now if the algorithm was called divide-sort you would be finished, but you still are missing the merge part.
You're still missing a merge. Merging is going to need a second temp array, I'll call it T and assume it's passed from main:
void divide(int A[], int T[], int n){
if(n < 2)
return;
if(n==2){
// ... swap A[0], A[1] if needed (the existing code is ok)
return;
}
divide(A, T, n/2); // recursively divide "left" half
divide(A+(n/2), T+(n/2), n-(n/2)); // recursively divide "right" half
merge(A, T, n/2, n) // merge the two halves
}
It might be simpler to assume that a partition 0 or 1 element is already sorted. Thus, it is enough to put as stop condition
if (n < 2)
return;
l changed my code but still cant figure out why it wont sort array...bubble sort only moves all elements one place to the right in my program instead of sorting array...l tired bsort and ssort and both do same thing shift elements for 1 position
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void bsort(int n,int a[])
{
int i,j,k;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1]);
{
k=a[j+1];
a[j+1]=a[j];
a[j]=k;
}
}
}
}
int main()
{
int i,j,k,m,n;
srand(time(0));
printf("Unesi broj clanova niza:");
scanf("%d",&n);
int a[n];
printf("Niz za sortiranje je:\n");
for(int i=0;i<n;i++) //Generisanje niza
{
a[i]=rand()%(81);
}
for(int i=0;i<n;i++)
{
printf("%3d",a[i]);
}
bsort(n,a);
printf("\n\nSortirani niz je:\n");
for(i=0;i<n;i++)
{
printf("%3d",a[i]);
}
}
There are several problems with your bubble sort implementation.
First, this line:
if (a[j] > a[j + 1]); {
is incorrect. The semi-colon terminates the conditional. As a result, the following block executes on every iteration of the inner loop and you end up unconditionally swapping a[j] and a[j+1] for every value of j. This means you're performing a nonsensical rearrangement of the array.
Second, you're not dealing correctly with edge cases in the inner loop. When j == 19, you access a[j+1], which is a[20], which is beyond the end of the array. You thus import garbage data into your array.
Lastly, even after correcting the above, your implementation is needlessly inefficient, in that your inner loop goes through the entire array on each iteration of the outer loop, which it doesn't have to. Hint: Try to think about how the initialization or termination condition of the inner loop could depend on i.
Update (after the OP's rewrite): You only addressed the second issue.
int main() {
int a[20];
srand(time(0));
// array values initialization
for (int i = 0; i < 19; i++) {
a[i] = rand() % (81);
}
// array sorting
bsort(a);
// array printing
for (int i = 0; i < 19; i++) {
printf("%3d", a[i]);
}
}