Just for fun I figured I'd solve the problem outlined here
Here's my solution:
Code:
#include <stdio.h>
#include <stdlib.h>
#define VCRUISE 400
#define AOPT 30
#define GPHOPT 2000
#define GPHEXTRA 10
#define CLIMBCOST 50
double tailwind(int altitude, int tail20, int tail40)
{
double windinc;
windinc = ((double)tail40 - tail20) / 20;
altitude -= 20;
return tail20 + windinc * altitude;
}
int climbcost(int climb)
{
return climb * CLIMBCOST;
}
double planespeed(double tailwind)
{
return VCRUISE + tailwind;
}
double legtime(int tailwind, int leglen)
{
return leglen / planespeed(tailwind);
}
int fuelconsumphour(int altitude)
{
int altdiff;
altdiff = AOPT - altitude;
if(altdiff < 0)
altdiff = -altdiff;
return GPHOPT + (GPHEXTRA * altdiff);
}
double fuelconsumpleg(int altitude, double ltime)
{
return climbcost(altitude) + fuelconsumphour(altitude) * ltime;
}
int main(void)
{
struct
{
int altitude;
double fuelcost;
} legs[10];
char buf[4096];
int nflights, nlegs;
int leglen, tail20, tail40;
int altitude;
double wind, legfuel, flightfuel, ltime;
int i, j;
fgets(buf, sizeof(buf), stdin);
nflights = atoi(buf);
for(i = 0;i < nflights;++i)
{
fgets(buf, sizeof(buf), stdin);
nlegs = atoi(buf);
for(j = 0;j < nlegs;++j)
{
fgets(buf, sizeof(buf), stdin);
sscanf(buf, "%d %d %d", &leglen, &tail20, &tail40);
for(altitude = 20;altitude <= 40;++altitude)
{
wind = tailwind(altitude, tail20, tail40);
ltime = legtime(wind, leglen);
legfuel = fuelconsumpleg(altitude, ltime);
if(altitude == 20 || legfuel < legs[j].fuelcost)
{
legs[j].altitude = altitude;
legs[j].fuelcost = legfuel;
}
}
}
printf("Flight %d: ", i+1);
for(flightfuel = 0, j = 0;j < nlegs;++j)
{
printf("%d ", legs[j].altitude);
flightfuel += legs[j].fuelcost;
}
printf("%.0f\n", flightfuel);
}
return 0;
}
For their test data I get this:
Code:
Flight 1: 35 20 15235
Flight 2: 20 30 30 26002
instead of what they get:
Code:
Flight 1: 35 30 13985
Flight 2: 20 30 40 23983
I can't seem to find what I'm doing wrong. I blame the fact that it's Monday. I tried some debugging. I threw a printf() in the middle of the altitude loop, but it looks right and the calculations add up. I'm beginning to think I'm misunderstanding the instructions, but I can't find my fault there either.
Anyone see what I'm missing?