I'm working on a simple algorithm problem for practice and i'm trying to figure out why on about 20 percent of test cases it fails. The problem is thus, given an array of ints find the average of all valid ints in the array.
An int is valid if
- It is greater than or equal to -273
- at least one of the previous two or next two ints are two points away from the current one
if the int is invalid it should not be included in calculating the average. Also, I don't believe the problem wants the solution to be cyclic (not sure though just thought about it while writing this so will try) i.e. if you are at the first int array[0], then there are no previous two ints as opposed to the last two being the previous two in a cyclic array.
my strategy is summed up in the code below:
public double averageTemperature(int[] measuredValues)
{
Queue<int> qLeft = new Queue<int>(2);
Queue<int> qRight = new Queue<int>(2);
double sum = 0d;
int cnt = 0;
for (int i = 0; i < measuredValues.Length; i++)
{
if (measuredValues[i] < -273)
continue;
if (qLeft.Count == 3)
qLeft.Dequeue();
for (int j = i + 1; j < measuredValues.Length; j++)
{
if (qRight.Count == 2)
{
break;
}
qRight.Enqueue(measuredValues[j]);
}
if (b(qLeft, qRight, measuredValues[i]) == true)
{
sum += measuredValues[i];
cnt++;
qLeft.Enqueue(measuredValues[i]);
}
qRight.Clear();
}
if (cnt > 0)
return sum / cnt;
return -300.0;
}
bool b(Queue<int> a, Queue<int> b, int c)
{
foreach (int q in a)
{
if (Math.Abs(q - c) <= 2)
return true;
}
foreach (int w in b)
{
if (Math.Abs(w - c) <= 2)
return true;
}
return false;
}
However, my strategy fails for this test case
{-13, 12, -14, 11, -15, 10, -16, 9, -17, 8, -18, 7, 6, -19, 5, -400, -400, 4, -390, -300, -270, 3, -12, 3, 2}
I don't understand why. I'm i missing something obvious? i know they're might be another more efficient way of solving this but i don't want to try them until i know why my "naive" way does not work.
Well I finally figured out why thanks to you guys. Here is my revised code for those who may find it helpful:
public double averageTemperature(int[] measuredValues)
{
Queue<int> qLeft = new Queue<int>(2);
Queue<int> qRight = new Queue<int>(2);
double sum = 0d;
int cnt = 0;
for (int i = 0; i < measuredValues.Length; i++)
{
if (qLeft.Count == 3)
qLeft.Dequeue();
for (int j = i + 1; j < measuredValues.Length; j++)
{
if (qRight.Count == 2)
{
break;
}
qRight.Enqueue(measuredValues[j]);
}
if (isValid(qLeft, qRight, measuredValues[i]) == true)
{
sum += measuredValues[i];
cnt++;
}
qLeft.Enqueue(measuredValues[i]);
qRight.Clear();
}
if (cnt > 0)
return sum / cnt;
return -300.0;
}
bool isValid(Queue<int> a, Queue<int> b, int c)
{
foreach (int q in a)
{
if (c >=-273 && Math.Abs(q - c) <= 2)
return true;
}
foreach (int w in b)
{
if (c >=-273 && Math.Abs(w - c) <= 2)
return true;
}
return false;
}