help with arrays

closed account (Dy0fSL3A)
Hey I am trying to write a function that does the following:
-------------------------------------------------------------------------
int positionOfMax(const string a[], int n);
Return the position of a string in the array such that that string is >= every string in the array. If there is more than one such string, return the smallest position of such a string. Return −1 if the array has no elements. For example:

string folks[6] = { "obiwan", "minnie", "han", "simba", "jabba", "ariel" };
int k = positionOfMax(folks, 6); // returns 3, since simba is latest
// in alphabetic order

-------------------------------------------------------------------------------
I figure i could so something like
1
2
3
4
5
6
7
8
9
int positionOfMax(const string a[], int n)
{
	for(int k = 0; k < n; k++)
	{
		if(a[k] >= a[n] && a[k] >= a[n-1]&& a[k] >= a[n-2]&& a[k] >= a[n-3] ... && a[k] >= a[n-n])
		return k;
	}
	return -1;
}

But a couple problems are that i dont know what n is and what if n is really large.
Anyone have an idea of what i could do?
closed account (Dy0fSL3A)
I came up with something i thought might work but it returns nothing for some reason. whats wrong with this
1
2
3
4
5
6
7
8
9
10
11
12
int positionOfMax(const string a[], int n)
{
		for (int k = 0; k<n; k++)
		{
			for(int j = n - 1; j >= 0 && a[k] >=a[j]; j--)
			{
					if(j=0)
					return k;
			}
		}
		return -1;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
int positionOfMax(const std::string a[], int in)
{
    if ( n == 0 )
        return -1 ;

    int max_index =0 ;
    for ( int i=1;  i<n;  ++i )
        if ( a[i] > a[max_index] )
            max_index = i ;

    return max_index ;
}


Don't over-think it.
closed account (Dy0fSL3A)
Damn thanks alot your method is much more straightforward, though I often fail to come up with something efficient like that myself
Topic archived. No new replies allowed.