Ronzii's Blog

Just your average geek's blog

Shortest distance between 2 Integers


#include <iostream>
#include <climits>
using namespace std;
int dist(int a[],int n, int x, int y)
{
    int a1=-1,a2=-1, min_distance = INT_MAX;
    for(int i=0;i<n;i++)
    {
        if(a[i]==x)
        {
            a1 = i;
            int distance = a1-a2;
            if(a2>=0 && distance<min_distance)
            {
                min_distance = distance;
            }
        }
        else if(a[i]==y)
        {
            a2 = i;
            int distance = a2-a1;
            if(a1>=0 && distance<min_distance)
            {
                min_distance = distance;
            }
        }
    }
    return min_distance;
}
int main()
{
    int a[] = {6,5,5,5,1,2,4,4,6,6,3,4,3,4,1,2,4};
    int size= sizeof(a)/sizeof(a[0]);
    cout<<dist(a,size,1,6);
    return 0;
}
Advertisements

March 29, 2012 - Posted by | C++ | , , , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s