how can i make this better..


Consider the problem of determining whether an arbitrary sequence x1, x2…….xN of N numbers
contains repeated occurrences of some number.



for (int i=0; i<n; i++)
{
For (int j=0; j<n; j++)
If (a[i]==a[j])
L=1;
}
If L==1 /* no repeation */
If L==0 /* repeation.*/
The algorithm for this is given by:
L=0;
for I, L->n
for J=0;
if a[i]=a[j]
L=1;
Last edited on
closed account (S6k9GNh0)
You can use the CODE BBCODE included on the forum.
adding code tags wouldn't hurt. =P

Other than that, you don't need to start 'j' from zero each time, that's wasteful (and will return false matches... like for example when i==j, then obviously a[i]==a[j]. If you're looping i from 0 to n, and looping j from 0 to n, you'll end up checking the same things multiple times. IE:

1
2
3
a[3] == a[5] // will be checked when i=3, j=5
a[5] == a[3] // will be checked when i=5, j=3 -- redundant!
a[3] == a[3] // checked when i=3 and j=3 -- false positive! 


If you want to get really snazzy you could break out of the loops after you found a match

Also, C++ is case sensitive. for and if. Not For or If. Here's a slightly improved version:

1
2
3
4
5
6
7
8
9
L = 0;
for(i = 0; (i < n) && !L; ++i)
{
  for(j = i+1; (j < n) && !L; ++j)
  {
    if(a[i] == a[j])
      L = 1;
  }
}
Last edited on
Thank-you, both of you.. :)
Topic archived. No new replies allowed.