Project Euler Solutions
digits.h
Go to the documentation of this file.
1 #ifndef DIGITS_H
2 #define DIGITS_H
3 
4 #include "macros.h"
5 #include "iterator.h"
6 
7 #include <stdlib.h>
8 #include <math.h>
9 
10 #ifdef DOXYGEN
11 namespace c::include::digits {
12 #endif
13 
18 struct digit_counter {
19  unsigned char *digits;
20  size_t idx;
21  IteratorTail(unsigned char, digit_counter)
22 };
23 
28 static unsigned char advance_digit_counter(digit_counter *dc) {
29  IterationHead(dc);
30  unsigned char ret = dc->digits[dc->idx--];
31  dc->exhausted = (dc->idx == -1);
32  return ret;
33 }
34 
40  if (dc->digits != NULL) {
41  free(dc->digits);
42  }
43 }
44 
48 digit_counter digits(uintmax_t n) {
49  const size_t digit_len = (size_t) ceil(log10((double) (n + 1)));
53  ExtendInit(digits, (unsigned char *) malloc(digit_len * sizeof(unsigned char))),
54  ExtendInit(idx, digit_len - 1)
55  );
56  for (size_t i = 0; i < digit_len; i++) {
57  ret.digits[i] = n % 10;
58  n /= 10;
59  }
60  return ret;
61 }
62 
63 
64 #ifdef DOXYGEN
65 };
66 #endif
67 
68 #endif
#define IteratorInitHead(advance,...)
The base macro for all iterator initialization functions in this project.
Definition: iterator.h:111
#define IteratorTail(return_type, struct_type)
The base definition macro for all iterators in this project.
Definition: iterator.h:46
bool exhausted
An indicator that the iterator has stopped.
Definition: iterator.h:231
size_t idx
Definition: digits.h:20
void free_digit_counter(digit_counter *dc)
Definition: digits.h:39
#define ExtendInit(name, value)
The extension macro for initializing more complicated Iterators.
Definition: iterator.h:168
digit_counter digits(uintmax_t n)
Definition: digits.h:48
#define AddDestructor(func)
The extension macro for initializing Iterators with a destructor.
Definition: iterator.h:145
#define IterationHead(it)
The base macro for all iteration functions in this project.
Definition: iterator.h:74
unsigned char * digits
Definition: digits.h:19
static unsigned char advance_digit_counter(digit_counter *dc)
Definition: digits.h:28
Definition: digits.h:18
Definition: digits.h:11
An implementation of Python-like iterators and generators using macros to maintain static typing...