costas.c
2.79 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <stdio.h>
#include <stdlib.h>
//#include <fcntl.h>
//#include <errno.h>
//#include <ctype.h>
#include <string.h>
#include "fdc_int.h"
// try to save on variables
static fd_int fd_const[MAX_VALUE + 1];
#define FD_CONST(n) (fd_const[n] ? fd_const[n] : (fd_const[n] = fd_new(n, n)))
//#define FD_CONST(n) fd_new(n, n)
/*
Costas arrays (communicated by Daniel Diaz)
*/
#define diffs(a, b) diffs[(a) * (N - 1) + (b)]
int main(int argc, char *argv[])
{
int solutions = 0, one_solution = 1;
int use_label = 0;
int i, j;
int verbose = 0;
fd_int *array, *diffs;
int N = 10;
int coeffs[] = { 1, 1, -1 };
fd_int diffeq[3];
int k;
fd_init(&argc, &argv);
for (i = 1; i < argc; ++i)
if (!strcmp(argv[i], "--all"))
one_solution = 0;
else if (!strcmp(argv[i], "--label"))
use_label = 1;
else if (!strncmp(argv[i], "-v", 2))
{
char *s = argv[i] + 1;
while (*s++ == 'v')
verbose++;
}
else if (isdigit(*argv[i]))
{
N = atoi(argv[i]);
i++;
break;
}
else
_fd_error("%s: unknown option `%s'\n", argv[0], argv[i]);
array = calloc(N, sizeof(*array));
for (j = 0; i < argc; ++j, ++i)
{
int a, b;
a = b = atoi(argv[i]);
if (strchr(argv[i], '-'))
b = atoi(strchr(argv[i], '-') + 1);
array[j] = (a == b) ? FD_CONST(a - 1) : fd_new(a - 1, b - 1);
}
for (; j < N; ++j)
array[j] = fd_new(0, N - 1);
fd_all_different(array, N);
if (use_label)
fd_label(array, N);
// differences:
// 0 <= array[] < N
// -> -(N-1) <= array[i] - array[j] <= N-1
// -> 0 <= array[i] - array[j] + N-1 <= 2*(N-1)
diffs = calloc((N - 2) * (N - 1), sizeof(*diffs));
for (i = 0; i < N - 2; ++i)
for (j = 0; j < N - 1 - i; ++j)
diffs(i, j) = fd_new(0, 2 * (N - 1));
diffeq[0] = FD_CONST(N - 1);
for (k = 1; k < N - 1; ++k)
{
for (i = k; i < N; ++i)
{
diffeq[1] = array[i];
diffeq[2] = array[i - k];
fd_poly_eq(coeffs, diffeq, 3, diffs(k - 1, i - k));
if (verbose >= 2)
printf("x[%d] - x[%d] -> (%d,%d)\n", i, i-k, k-1, i-k);
}
fd_all_different(&diffs(k - 1, 0), N - k);
}
while (fd_solve() == FD_OK)
{
printf("solution %d:\n", ++solutions);
for (i = 0; i < N; ++i)
{
printf("%d", fd_var_value(array[i]) + 1);
if (i != N - 1)
putchar(' ');
}
putchar('\n');
if (verbose >= 1)
for (k = 1; k < N - 1; ++k)
{
printf("%*s", k, "");
for (i = k; i < N; ++i)
printf("%d ", fd_var_value(diffs(k - 1, i - k)) - (N - 1));
putchar('\n');
}
#if !(defined(LOCAL_SEARCH) || defined(DISTRIBUTED_SOLVER))
if (one_solution)
#endif
break;
}
if (solutions)
printf("%d solutions found\n", solutions);
else
printf("inconsistent CSP\n");
fd_end();
return !solutions;
}