-
Notifications
You must be signed in to change notification settings - Fork 0
/
015.c
88 lines (68 loc) · 1.86 KB
/
015.c
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
// Starting in the top left corner in a 20 by 20 grid, how many routes are there to the bottom right corner?
#include <stdio.h>
#include <stdbool.h>
#include <math.h>
int main () {
double latticePaths(const int n);
double factorial(int n);
printf("%f\n", latticePaths(20));
return 0;
}
// Calculate the central binomial coefficient
double latticePaths(const int n) {
double factorial(int n);
return (factorial(2 * n)) / pow(factorial(n), 2);
}
// Calculate factorial of n
double factorial(int n) {
double product = 1;
while (n > 0) {
product *= n--;
}
return product;
}
//// Below are the naive implementations that didn't work
// Count routes on grid of size n, starting from node {r, c}
void bruteCountRoutes(const int size, const int r, const int c,
long int *count) {
if (r == size && c == size) { // reached an edge
*count += 1;
}
if (r < size) {
bruteCountRoutes(size, (r + 1), c, count);
}
if (c < size) {
bruteCountRoutes(size, r, (c + 1), count);
}
}
long int routeCount(const int grid_size) {
bool incrementDigit(int arr[], int i, int limit);
long int count = 1;
int lastdigit_i = grid_size - 1;
int arr[grid_size];
// Initialize array
for (int i = 0; i < grid_size; i++) {
arr[i] = 0;
}
while (incrementDigit(arr, lastdigit_i, grid_size) == true) {
count++;
}
return count;
}
// Increment the i-th digit of a digit array.
// Carries over when necessary
bool incrementDigit(int arr[], int i, int limit) {
if (i == 0 && arr[0] == limit) { // reached max value
return false;
} else if (arr[i] == limit) { // carry over to preceeding digit
if (incrementDigit(arr, i - 1, limit) == false) { // reached max value
return false;
} else {
arr[i] = arr[i - 1];
return true;
}
} else {
arr[i]++;
return true;
}
}