Blame view

src/csps/schurs.c 1.83 KB
94b2b13d   Pedro Roque   PHACT source
1
2
3
4
/*
 * schurs.c
 *
 *  Created on: 18/11/2017
4d26a735   Pedro Roque   Increased recogni...
5
 *      Author: pedro
94b2b13d   Pedro Roque   PHACT source
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 *
 *      https://github.com/MiniZinc/minizinc-benchmarks/blob/master/schur_numbers/schur.mzn
 *
 *		Schurs numbers:
 *		Determine if N balls labelled 0..n-1 can be placed in K boxes with
 *		no box containing a triple {x,y,z} where x+y=z
 */

#include "schurs.h"

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

#include "../config.h"
4d26a735   Pedro Roque   Increased recogni...
22
23
#include "../constraints/ne.h"
#include "../constraints/bool_or.h"
94b2b13d   Pedro Roque   PHACT source
24
25
26
27
28
29
#include "../split.h"
#include "../variables.h"

/*
 * Solve the Schurs numbers problem with N values
 */
4d26a735   Pedro Roque   Increased recogni...
30
void run_schurs(int* csp_dims) {
94b2b13d   Pedro Roque   PHACT source
31
32
33
34
35
36
37
38
39
40
	int k = csp_dims[0];
	int n = csp_dims[1];
	unsigned long result;
	unsigned int *box;
	unsigned int reif[3];
	unsigned int or_v_id;
	int i, j;

	// N - number of balls
	// K - number of boxes
4d26a735   Pedro Roque   Increased recogni...
41
	box = malloc((unsigned long)n * sizeof(unsigned int));
94b2b13d   Pedro Roque   PHACT source
42
43

	for (i = 0; i < n; i++) {
4d26a735   Pedro Roque   Increased recogni...
44
		box[i] = v_new_range(0, (unsigned int)k - 1, true);
94b2b13d   Pedro Roque   PHACT source
45
46
47
48
49
50
51
52
53
	}

	or_v_id = v_new_val(1);
	for (i = 1; i < n; i++) {
		for (j = i + 1; j < n - i + 1; j++) {
			reif[0] = v_new_range(0, 1, false);
			reif[1] = v_new_range(0, 1, false);
			reif[2] = v_new_range(0, 1, false);

4d26a735   Pedro Roque   Increased recogni...
54
55
56
			c_ne_reif(box[i - 1], box[j - 1], (int)reif[0]);
			c_ne_reif(box[i - 1], box[i + j - 1], (int)reif[1]);
			c_ne_reif(box[j - 1], box[i + j - 1], (int)reif[2]);
94b2b13d   Pedro Roque   PHACT source
57

4d26a735   Pedro Roque   Increased recogni...
58
			c_bool_or(reif, 3, or_v_id);
94b2b13d   Pedro Roque   PHACT source
59
60
61
62
63
64
65
66
67
68
69
70
71
72
		}
	}

	if (FINDING_ONE_SOLUTION) {
		printf("\nFinding one solution for Schurs numbers with %u balls and %u boxes.\n", n, k);
	} else {
		printf("\nCounting all the solutions for Schurs numbers with %u balls and %u boxes.\n", n, k);
	}

	// Solve the CSP
	result = solve_CSP();

	if (FINDING_ONE_SOLUTION && result == 1) {
		printf("Solution:\n");
4d26a735   Pedro Roque   Increased recogni...
73
		vs_print_single_val(box, (unsigned int)n, 1);
94b2b13d   Pedro Roque   PHACT source
74
75
76
77
78
79
80
		printf("\n");
	} else {
		printf("%lu solution(s) found\n", result);
	}

	free(box);
}