Jump to content
  • Advertisement
Sign in to follow this  
Alpha_ProgDes

Codility sample question

This topic is 2762 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I tried to post in the other two threads about it, but they're retired.
So long story, short. Why is this wrong? I didn't see the sample array they used to test the code so I had to go by was the sample array they had.

int equi ( int[] A ) {
long equiIndex = -1;
long equiTotal = 0;

if (A.Length == 0)
{
return (int)equiIndex;
}

if (A == null)
{
return (int)equiIndex;
}

foreach (int i in A)
{
equiTotal += i;
}

for (long j = 0; j < A.Length; ++j)
{
if (A[j] == - (equiTotal - A[j]))
{
equiIndex = j;
break; //even with this still wrong
}
}

return (int)equiIndex;
}




[Edited by - Alpha_ProgDes on December 25, 2010 9:54:54 AM]

Share this post


Link to post
Share on other sites
Advertisement
I can see a few problems offhand:

  • A.Length is accessed before checking if A is null (crash)

  • Cast from long to int may fail for very large arrays

  • The algorithm is wrong. Think carefully about what you're trying to do (find the equilibrium index, i.e. the sum of the first chunk of the array equals the sum of the remainder of the array) and compare this to what you're actually testing for.


This might be easier if you compare to the actual solutions provided in other languages here (even if you don't know Python, understanding the algorithm should be trivial).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!