'is it wrong to start an array from 1?
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;
}
Solution 1:[1]
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-1elements because in memory an array's first element is at index0.Some of the default array functions like
beginandsizewill 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rupakshi |
