aboutsummaryrefslogtreecommitdiff
path: root/src/calculer.c
blob: 6ed59837c12534f1eec12fdbb0199495dc79b3c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
 * Copyright (C) 2024  Tristan Riehs
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#include <readline/readline.h>

static int lower = 0;
static int upper = 100;

static FILE *logfile;

/* Return a random number x such that lower <= x < upper. */
static int
calculer_rand(void)
{
	return lower + rand()%(upper-lower);
}

static void *
measure_before(void)
{
	/* TODO: measure time in ms */
	return (void *) time(NULL);
}

int
measure_after(void *data)
{
	int t0 = (intptr_t) data;
	time_t now = time(NULL);
	int dt = now - t0;
	char buf[64] = {0};
	struct tm *tm = localtime(&now);
	size_t bytes_written = strftime(buf, sizeof(buf), "%F\t", tm);
	assert(bytes_written);
	bytes_written += sprintf(buf + bytes_written, "%d\n", dt);

	return bytes_written != fwrite(buf, 1, bytes_written, logfile);
}

int
main(void)
{
	char prompt[31] = {0};
	int x, y, res;
	char *input;

	logfile = fopen("./calculer.log", "a");
	assert(logfile);

	while (1)
	{
		x = calculer_rand();
		y = calculer_rand();
		void *measure_data = measure_before();
		res = x+y;
		assert(!measure_after(measure_data));
		sprintf(prompt, "%d + %d = ", x, y);
		input = readline(prompt);

		if (strcmp(input, "q") == 0)
		{
			free(input);
			fclose(logfile);
			exit(0);
		}

		if (atoi(input) == res)
			printf("RIGHT\n");
		else
			printf("WRONG\n");

		free(input);
	}

	fclose(logfile);
	return 0;
}