all_interval.c 2.68 KB
/*
 * all_interval.c
 *
 *  Created on: 15/04/2017
 *      Author: pedro
 *
 *      https://www.cril.univ-artois.fr/~lecoutre/benchmarks.html#
 *      http://www.csplib.org/Problems/prob007/
 *
 *      All Interval Series problem:
 *      Given the twelve standard pitch-classes (c, c#, d, …), represented by numbers 0,1,…,11,
 *      find a series in which each pitch-class occurs exactly once and in which the musical intervals
 *      between neighbouring notes cover the full set of intervals from the minor second (1 semitone)
 *      to the major seventh (11 semitones). That is, for each of the intervals, there is a pair of
 *      neigbhouring pitch-classes in the series, between which this interval appears.
 */

#include "all_interval.h"

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#include "../config.h"
#include "../constraints/fake_all_different.h"
#include "../constraints/lt.h"
#include "../constraints/var_eq_minus_abs.h"
#include "../split.h"
#include "../variables.h"

/*
 * Solve an instance of All Interval problem with N values
 */
void run_all_interval(int* csp_dims) {
	int n = csp_dims[0];
	unsigned long result;
	int i;

	// vectors with the variables ID
	unsigned int* x_vs = malloc((unsigned int)n * sizeof(unsigned int));
	unsigned int* diff_vs = malloc(((unsigned int)n - 1) * sizeof(unsigned int));

	// Create the CSP variables
	for (i = 0; i < n; i++) {
		x_vs[i] = v_new_range(1, (unsigned int)n, true);
	}

	for (i = 0; i < n - 1; i++) {
		diff_vs[i] = v_new_range(1, (unsigned int)n - 1, false);
	}

	// Create the all_different constraints
	c_fake_all_different(x_vs, (unsigned int)n);
	c_fake_all_different(diff_vs, (unsigned int)n - 1);

	//unsigned int reif[2];

	// VAR_EQ_MINUS_ABS
	for (i = 0; i < n - 1; i++) {
		c_var_eq_minus_abs(diff_vs[i], x_vs[i + 1], x_vs[i]);

		/*reif[0] = v_new_range(0, 1, false);
		reif[1] = v_new_range(0, 1, false);
		c_var_eq_minus_reif(diff_vs[i], x_vs[i + 1], x_vs[i], reif[0]);
		c_var_eq_minus_reif(diff_vs[i], x_vs[i], x_vs[i + 1], reif[1]);
		c_ne(reif[0], reif[1]);*/
	}

	// symmetry breaking
	c_lt(x_vs[0], x_vs[n - 2]);
	c_lt(diff_vs[0], diff_vs[1]);

	if (FINDING_ONE_SOLUTION) {
		printf("\nFinding one solution for the all interval series with %u values.\n", n);
	} else {
		printf("\nCounting all the solutions for the all interval with %u values.\n", n);
	}

	// Solve the CSP
	result = solve_CSP();

	if (FINDING_ONE_SOLUTION && result == 1) {
		printf("Solution:\n");

		printf("{");
		for (i = 0; i < n - 1; i++) {
			printf("%u(%u),", v_get_value(x_vs[i]), v_get_value(diff_vs[i]));
		}
		printf("%u}\n", v_get_value(x_vs[n - 1]));

	} else {
		printf("%lu solution(s) found\n", result);
	}

	free(x_vs);
	free(diff_vs);
}