106 lines
2.4 KiB
C
106 lines
2.4 KiB
C
#include <stdio.h>
|
|
#include <stdint.h>
|
|
#include <stdbool.h>
|
|
#include <stdlib.h>
|
|
#include <math.h>
|
|
|
|
#define DEFAULT_FILE "input3.txt"
|
|
#define STRBUF_LEN 200
|
|
#define ISDIGIT(X) (X >= '0' && X <= '9')
|
|
|
|
#define NUM_RACES 1
|
|
|
|
uint64_t parse_num(char *str)
|
|
{
|
|
uint64_t num = 0;
|
|
while (ISDIGIT(*str))
|
|
{
|
|
num = (num * 10) + (*str - '0');
|
|
str++;
|
|
}
|
|
return num;
|
|
}
|
|
|
|
void parse_line(char *str, uint64_t *nums)
|
|
{
|
|
uint64_t race = 0;
|
|
|
|
for (race = 0; race < NUM_RACES; race++)
|
|
{
|
|
while (!ISDIGIT(*str)) str++;
|
|
nums[race] = parse_num(str);
|
|
while (ISDIGIT(*str)) str++;
|
|
}
|
|
}
|
|
|
|
// Solves for the 0-intersection points, placing the results in result1 and result2.
|
|
// Returns true if it can be solved, returns false if it is unsolvable.
|
|
bool solve_quadratic(uint64_t time, uint64_t distance, uint64_t *result1, uint64_t *result2)
|
|
{
|
|
double doubleres1;
|
|
double doubleres2;
|
|
int64_t s = (time * time) - (4 * distance);
|
|
if (s < 0) return false;
|
|
doubleres1 = ( time - sqrt(s) ) / 2;
|
|
doubleres2 = ( time + sqrt(s) ) / 2;
|
|
|
|
if (doubleres1 == (double)(ceil(doubleres1))) doubleres1 += 1;
|
|
*result1 = ceil(doubleres1);
|
|
|
|
if (doubleres2 == (double)(floor(doubleres2))) doubleres2 -= 1;
|
|
*result2 = floor(doubleres2);
|
|
return true;
|
|
}
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
// Get filename as an argument, if there is one
|
|
char *path = (argc > 1) ? argv[1] : DEFAULT_FILE;
|
|
|
|
if (!path)
|
|
{
|
|
printf("Requires input file.\n");
|
|
return 1;
|
|
}
|
|
|
|
FILE *file = fopen(path, "r");
|
|
char strbuf[STRBUF_LEN] = {0};
|
|
|
|
if (!file)
|
|
{
|
|
printf("Could not find file.");
|
|
return 1;
|
|
}
|
|
|
|
uint64_t times[NUM_RACES] = {0};
|
|
uint64_t dists[NUM_RACES] = {0};
|
|
uint64_t results[NUM_RACES] = {0};
|
|
|
|
fgets(strbuf, STRBUF_LEN, file);
|
|
parse_line(strbuf, times);
|
|
|
|
fgets(strbuf, STRBUF_LEN, file);
|
|
parse_line(strbuf, dists);
|
|
|
|
uint64_t i = 0;
|
|
uint64_t multiplied = 1;
|
|
|
|
for (i = 0; i < NUM_RACES; i++)
|
|
{
|
|
uint64_t res1;
|
|
uint64_t res2;
|
|
if (!solve_quadratic(times[i], dists[i], &res1, &res2))
|
|
{
|
|
printf("Error?? Invalid quadratic.\n");
|
|
return 1;
|
|
}
|
|
|
|
results[i] = res2 - res1 + 1;
|
|
printf("%lu ", results[i]);
|
|
multiplied *= results[i];
|
|
}
|
|
|
|
printf("\nMultiplied: %lu\n", multiplied);
|
|
|
|
return 0;
|
|
} |