Codility Programmer Lessons - 03/Q3 (TapeEquilibrium)

preview_player
Показать описание
Line by line walkthrough to hit 100% on Codility.
Lesson 03 - Q3 TapeEquilibrium

Happy coding :D

- Tariq Albajjali
Рекомендации по теме
Комментарии
Автор

Hi
Your below condition not not covering one case which is echo solution([-1001, 1001]);
if ($A[$i] < -abs(1000) || $A[$i] > 1000) {
return 0;
}
You need this condition before first two elements sum as well.
if ( $A[0] < -abs(1000) || $A[0] > 1000 || $A[1] < -abs(1000) || $A[1] > 1000) {
return 0;
}

furqan
Автор

python solution
def solution(a):
differences = []
i=0
a_len = len(a)
while i < a_len-1:
difference = abs(sum(a[:i+1]) - sum(a[i+1:]))

i += 1
return min(differences)

GiPa
Автор

Your condition doesn't check the first and the last element of the array, because you do a check inside of the loop, where you check all the elements except first and the last one. Strange that you got 100% score in such case.

igorzhovtaniuk
Автор

The equation throws me off (confused confused confused). Took 30 minute to understand the problem and 5 minutes to solve it. LOL .

xiaowooyc
Автор

It was really helpful, but I have a question In the last condition that's is the number should be between (-1000, 1000) you check it In loop but you're forget that (i) is less than Array (length - 1) it'll not check the last element in array, am I right ? or I miss something

codeon
Автор

It's not a problem to process the last element. You're going to have the sum of the whole array on one side, and 0 on the other, so it will by definition always be bigger than all the other differences. Also you named your variable "sum" but it's actually a difference. Also you could just put the whole sum in your "right" variable and start at the first element. You're adding complexity for nothing, it's not significant that you add 2 iterations (one for the first element, one for the last element). Also, you actually need to check the difference for the first element, but you're skipping it.

philtrem
Автор

C#.NET example
public static int Solution4(int[] values)
{
int retVal = 0;
for (int i = 1; i < values.Length; ++i)
{
int firstValue = values.Take(i).Sum();
int secondValue = values.Skip(i).Sum();
int absoluteValue = (firstValue - secondValue) < 0 ? -1 * (firstValue - secondValue) : firstValue - secondValue;
if (absoluteValue == 0)
{
return absoluteValue;
}
if (i == 1)
{
retVal = absoluteValue;
}
retVal = retVal < absoluteValue ? retVal : absoluteValue;
}
return retVal;
}

MalleshGali