c,algorithm,scheduling,reduction,sat , Class Scheduling to Boolean satisfiability [Polynomial-time reduction]

Class Scheduling to Boolean satisfiability [Polynomial-time reduction]


Tag: c,algorithm,scheduling,reduction,sat

I have some theorical/practical problem and I don't have clue for now on how to manage, Here it is:

I create a SAT solver able to find a model when one is existing and to prove the contradiction when it's not the case on CNF problems in C using genetics algorithms.

A SAT-problem looks basically like this kind of problem : enter image description here My goal is to use this solver to find solutions in a lot of differents NP-completes problems. Basically, I translate differents problems into SAT, solve SAT with my solver and then transforme the solution into a solution acceptable for the original problem.

I already succeed for the N*N Sudoku and also the N-queens problems, but here is my new goal : to reduce the Class Scheduling Problem to SAT but I have no idea how to formalize a class-scheduling problem in order to easily transform it in SAT after.

The goal is obviously, in few months, to generate a picture of a schedule like this one :

enter image description here

I found this source-code who is able to solved the class-scheduling but without any reductions to SAT unfortunately :/

I also found some articles about Planning in general (http://www.cs.rochester.edu/users/faculty/kautz/papers/kautz-satplan06.pdf for instance).

But the planning domain definition language used in this article seems quite too general for me to represents a Class-scheduling problem. :/

Does someone has an idea on how to formalize efficiently a Class-scheduling in order to reduce it to SAT and after, transform the SAT solution (if it exists ^^) into a Class-schedule ?

I'm basically open to any suggestions, I for now have no idea on how to represents, how to reduce the problem, how to transform the SAT-solution into a schedule...

Thanks in advance for everyone who will spend some times on my problem, Best regards,


I am going to try and first formalize the problem, and then attempt to reduce it to SAT.

Define the class scheduling problem as:

Input = { S1,S2,....,Sn | Si = {(x_i1, y_i1), (x_i2, y_i2) , ... , (x_ik, y_ik) | 0 <= x_ij < y_ij <= M } } 

Informally: The input is a set of classes, each class is a set of (open) intervals in the form (x,y)
(M is some constant that describes the "end of the week")

Output: True if and only if there exists some set:

R = { (x_1j1, y_1j1) , ..., (x_njn, y_njn) | for each a,b: (x_aja,y_aja) INTERSECTION (x_bjb,y_bjb) = {} }

Informally: true if and only if there is some assignment of intervals such that the intersection between each pair of intervals is empty.

Reduction to SAT:

Define a boolean variable for each interval, V_ij
Based on it, define the formula:

F1 = (V_11 OR V_12 OR ... OR V_1(k_1)) AND .... AND (V_n1 OR V_n2 OR ... OR V_n(k_n))

Informally, F1 is satisfied if and only if at least one of the interval for each class is "satisfied"

Define Smaller(x,y) = true if and only if x <= y1
We will use it to make sure intervals don't overlap.
Note that if we want to make sure (x1,y1) and (x2,y2) don't overlap, we need:

x1 <= y1 <= x2 <= y2 OR  x2 <= y2 <= x1 <= y1

Since the input guarantees x1<=y1, x2<=y2, it reduces to:

y1<= x2 OR y2 <= x1

And using our Smaller and boolean clauses:

Smaller(y1,x2) OR Smaller(y2,x1)

Now, let's define new clauses to handle with it:

For each pair of classes a,b and intervals c,d in them (c in a, d in b)

G_{c,d} = (Not(V_ac) OR Not(V_bd) OR Smaller(y_ac,x_bd) OR Smaller(y_bd,x_ac))

Informally, if one of the intervals b or d is not used - the clause is satisfied and we are done. Otherwise, both are used, and we must ensure there is no overlap between the two intervals.
This guarantees that if both c,d are "chosen" - they do not overlap, and this is true for each pair of intervals.

Now, form our final formula:

F = F1 AND {G_{c,d} | for each c,d}

This formula ensures us:

  1. For each class, at least one interval is chosen
  2. For each two intervals c,d - if both c and d are chosen, they do not overlap.

Small note: This formula allows to chose more than 1 interval from each class, but if there is a solution with some t>1 intervals, you can easily remove t-1 of them without changing correctness of the solution.

At the end, the chosen intervals are the boolean variables V_ij we defined.


Alebgra = {(1,3),(3,5),(4,6)} Calculus = {(1,4),(2,5)}

Define F:

F = (V1,1 OR V1,2 OR V1,3) AND (V2,1 OR V2,2)

Define G's:

G{A1,C1} = Not(V1,1) OR Not(V2,1} OR  4 <= 1 OR 3 <= 1 //clause for A(1,3) C(1,4)
         = Not(V1,1) OR Not(V2,1} OR false = 
         = Not(V1,1) OR Not(V2,1}
G{A1,C2} = Not(V1,1) OR Not(V2,2} OR  3 <= 2 OR 5 <= 1 // clause for A(1,3) C(2,5)
         = Not(V1,1) OR Not(V2,2} OR false = 
         = Not(V1,1) OR Not(V2,2} 
G{A2,C1} = Not(V1,2) OR Not(V2,1} OR  5 <= 1 OR 4 <= 3 //clause for A(3,5) C(1,4)
         = Not(V1,2) OR Not(V2,1} OR false = 
         = Not(V1,2) OR Not(V2,1}
G{A2,C2} = Not(V1,2) OR Not(V2,2} OR  5 <= 2 OR 5 <= 3 // clause for A(3,5) C(2,5)
         = Not(V1,2) OR Not(V2,2} OR false = 
         = Not(V1,2) OR Not(V2,2} 
G{A3,C1} = Not(V1,3) OR Not(V2,1} OR  4 <= 4 OR 6 <= 1 //clause for A(4,6) C(1,4)
         = Not(V1,3) OR Not(V2,1} OR true= 
         = true
G{A3,C2} = Not(V1,3) OR Not(V2,2} OR  6 <= 2 OR 5 <= 4 // clause for A(4,6) C(2,5)
         = Not(V1,3) OR Not(V2,2} OR false = 
         = Not(V1,3) OR Not(V2,2} 

Now we can show our final formula:

    F = (V1,1 OR V1,2 OR V1,3) AND (V2,1 OR V2,2) 
        AND  Not(V1,1) OR Not(V2,1} AND Not(V1,1) OR Not(V2,2}
        AND  Not(V1,2) OR Not(V2,1} AND Not(V1,2) OR Not(V2,2}
        AND  true AND Not(V1,3) OR Not(V2,2}

The above is satisfied only when:

V1,1 = false
V1,2 = false
V1,3 = true
V2,1 = true
V2,2 = false

And that stands for the schedule: Algebra=(4,6); Calculus=(1,4), as desired.

(1) can be computed as a constant to the formula pretty easily, there are polynomial number of such constants.


free causing different results from malloc

Below is a C program i have written to print different combination of characters in a string. This is not an efficient way as this algorithm creats a lot of extra strings. However my question is NOT about how to solve this problem more efficiently. The program works(inefficiently though) and...

What is this algorithm mapping coordinates to numbers called?

I'm writing a program for visualizing crystals. As a part of the program, I have to generate all different basic points in a lattice structure. For those that aren't familiar with crystallography, you can find the most general cases of these structures here: https://en.wikipedia.org/wiki/Hermann%E2%80%93Mauguin_notation#Lattice_types The problem was that I wanted...

Should checking loop conditions be counted towards total number of comparisons?

I have implemented three different sorting algorithms and now I want to confirm that my approach of counting the total number of comparisons is correct. In my mind, the number of comparisons shouldn't be tied to the conditional branches because if the condition isn't met, the comparison was still made...

How to control C Macro Precedence

#define VAL1CHK 20 #define NUM 1 #define JOIN(A,B,C) A##B##C int x = JOIN(VAL,NUM,CHK); With above code my expectation was int x = 20; But i get compilation error as macro expands to int x = VALNUMCHK; // Which is undefined How to make it so that NUM is replaced first...

Counting bytes received by posix read()

I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at http://linux.die.net/man/3/read, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

How does ((a++,b)) work? [duplicate]

This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

Getting Wrong Answer in “Longest non regular parentheses sub-sequence ”codechef june cook off

I attended a programming competition(it has ended now). I don't know why my solution is giving WA, I read the editorial, saw other people solution but unable to find a flaw in my solution. Obviously I am missing somewhere. Please help! Question Link My Solution My approach If the pattern...

C++ / C #define macro calculation

Suppose I have #define DETUNE1 sqrt(7)-sqrt(5) #define DETUNE2 sqrt(11)-sqrt(7) And I call these multiple times in my program. Are DETUNE1 and DETUNE2 calculated every time it is called? Thanks. Please don't downvote this, I really want to know and a search didn't turn up anything definite. ...

How to give mathemarical proof or support my answer through reasoning as a general case?

You are managing a software project that involves building a computer-assisted instrument for medical surgery. The exact placement of the surgical knife is dependent on a number of different parameters, usually at least 25, sometimes more. Your programmer has developed two algorithms for positioning the cutting tool, and is seeking...

Text justification C language

I have to solve a problem that involves left justification string length and leading zeros. I have the following table : BEGIN CLOSE CONCATENATE DELETE END INITIALIZE PRINT WRITE This is produced by a simple program. My problem is to find out how to convert it like that : It...

Does strlen() always correctly report the number of char's in a pointer initialized string?

As long as I use the char and not some wchar_t type to declare a string will strlen() correctly report the number of chars in the string or are there some very specific cases I need to be aware of? Here is an example: char *something = "Report all my...

What all local variables goto Data/BSS segment?

The man page of nm here: MAN NM says that The symbol type. At least the following types are used; others are, as well, depending on the object file format. If lowercase, the symbol is usually local; if uppercase, the symbol is global (external) And underneath it has "b" and...

How does this code print odd and even?

#define MACRO(num, str) {\ printf("%d", num);\ printf(" is");\ printf(" %s number", str);\ printf("\n");\ } int main(void) { int num; printf("Enter a number: "); scanf("%d", &num); if (num & 1) { MACRO(num, "Odd"); } else { MACRO(num, "Even"); } return 0; } Please explain the above code (if/else condition and how...

C language, vector of struct, miss something?

This is a part of my program that I want to create a vector of struct typedef struct { char nome[501]; int qtd; int linha; int coluna; } tPeca; tPeca* criarPecas(FILE *pFile, int tam) { int i; tPeca *pecaJogo = (tPeca*)malloc(tam*sizeof(tPeca)); if (pecaJogo == NULL) return NULL; for (i =...

How can I align stack to the end of SRAM?

I have a STM32F103VCT6 microcontroller with 48kb of SRAM, and recently i've got a memory collision: I have some static variable (lets call it A) located in heap with size of 0x7000 and I wrote some simple function to get info about stack and heap: void check(int depth) { char...

OpenGL glTexImage2D memory issue

I'm loading a cubemap to create a skybox, everything is fine and the skybox renders properly with a correct texture application. However, I decided to check my program safety with valgrind, Valgrind gives this error: http://pastebin.com/seqmXjyx The line 53 in sky.c is: glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, texture.width, texture.height, 0,...

Does realloc() invalidate all pointers?

Note, this question is not asking if realloc() invalidates pointers within the original block, but if it invalidates all the other pointers. I'm new to C, and am a bit confused about the nature of realloc(), specifically if it moves any other memory. For example: void* ptr1 = malloc(2); void*...

Dynamic programming: how to design algorithm for when there are two factors to consider?

I have the following problem and I only have a slight idea about it: Consider a tape storage problem. Given n files of length l1,...,ln and frequencies with which they are accessed f1,...,fn, where sum of all frequencies is 1 and 0<fi<1. "Optimal" means to minimize the average retrieval time...

C programming - Confusion regarding curly braces

The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces. This one is actually running fine: #include <stdio.h> #include <stdlib.h> int main() { int ch, lastch; lastch = 'a'; while((ch = getchar())!= EOF)...

CGO converting Xlib XEvent struct to byte array?

I am creating a simple window manager (code based of the c code in tinywm) in Golang. To use Xlib, I am using cgo, so my header is: // #cgo LDFLAGS: -lX11 // #include <X11/Xlib.h> And I have a variable declaration, like: event := C.XEvent{} And then, I use this...

Infinite loop with fread

I'm trying to allocate an array 64 bytes in size and then loop over the array indexes to put a read a byte each from the inputfile. but when I don't malloc() the array indexes, the loop stays in index0 (so each time it loops it replaces the content in...

Disadvantages of calling realloc in a loop

I'm trying to implement some math algorithms in C on Windows 7, and I need to repeatedly increase size of my array. Sometimes it fails because realloc can't allocate memory. But if I allocate a lot of memory at once in the beginning it works fine. Is it a problem...

Loop through database table and compare user input

I am trying to loop through the rows in a MySql table and compare the data in a certain column to some user input using C. Currently my code looks like this: MYSQL *cxn = mysql_init(NULL); MYSQL_RES *result; unsigned int num_fields; unsigned int num_rows; char *query_string; MYSQL_ROW *row; if (mysql_real_connect(cxn,...

Array breaking in Pebble C

I'm trying to create a simple dice-rolling application in Pebble using C on CloudPebble. I have an array of different die sizes you can scroll through using Up/Down, and you roll (currently just generate a random number, it'll get fancier later) using the middle button. There's also a label at...

Does there exist an algorithm for iterating through all strings that conform to a particular regex?

I'm making a script to try and hack into an account whose login password is at least 8 characters long and includes at least 1 number, 1 special character and 1 capital letter. I will use brute force. Is there a compact, elegant and efficient way to iterate through every...

Galois LFSR - how to specify the output bit number

I am trying to understand how change the galois LFSR code to be able to specify the output bit number as a parameter for the function mentioned below. I mean I need to return not the last bit of LFSR as output bit, but any bit of the LFSR (...

Algorithm for [inclusive/exclusive]_scan in parallel proposal N3554

Proposal N3554 (A Parallel Algorithms Library) for C++14, proposes (among other things), what seem to be parallel versions of the current std::partial_sum, e.g.: template< class ExecutionPolicy, class InputIterator, class OutputIterator, class BinaryOperation> OutputIterator inclusive_scan( ExecutionPolicy &&exec, InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); With the explanation Effects: For each...

Is there Predefined-Macros define about byte order in armcc

Is there Predefined-Macros define about byte order in armcc. I am a novice on the armcc.and sorry for my English. In gcc these are macros: __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__ __ORDER_BIG_ENDIAN__ __ORDER_PDP_ENDIAN__ ... Now I have to use armcc, Is there same like these with armcc? Thank a lot. by the way,the armcc...

3 X 3 magic square recursively

I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

Segmentation fault with generating an RSA and saving in ASN.1/DER?

#include <string.h> #include <openssl/aes.h> #include <openssl/rand.h> #include <openssl/bio.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/pem.h> #define RSA_LEN 2048 #define RSA_FACTOR 65537 int genRSA2048(unsigned char **pub,unsigned int *pub_l,unsigned char **priv,unsigned int *priv_l){ RSA *pRSA = NULL; pRSA = RSA_generate_key(RSA_LEN,RSA_FACTOR,NULL,NULL); if (pRSA){ pub_l = malloc(sizeof(pub_l)); *pub_l = i2d_RSAPublicKey(pRSA,pub); priv_l = malloc(sizeof(priv_l));...

Program to reverse a string in C without declaring a char[]

I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, Please help! int main() { char* name=malloc(256); printf("\nEnter string\n"); scanf("%s",name); printf("\nYou entered%s",name); int i,count; count=0; //find the...

CallXXXMethod undefined using JNI in C

So I've tried to use the JNI interface to call Java methods from C. Calling static methods is no problem, but I get stuck when I want to call a method on an object. The code is as follows: #include <stdio.h> #include <string.h> #include <jni.h> int main() { JavaVMOption options[1];...

What does `strcpy(x+1, SEQX)` do?

I'm wondering what this syntax of strcpy() does in line 65 and 66: 24 #define SEQX "TTCATA" 25 #define SEQY "TGCTCGTA" 61 M = strlen(SEQX); 62 N = strlen(SEQY); 63 x = malloc(sizeof(char) * (M+2)); /* +2: leading blank, and trailing \0 */ 64 y = malloc(sizeof(char) * (N+2)); 65...

How to increment the value of an unsigned char * (C)

I have a value stored as an unsigned char * (in C). This holds the SHA1 hash of a string. My goal is to cover the SHA1 key space. Since I'm using <openssl/evp.h> to generate the hashes, I end up with an unsigned char* holding the SHA1 value. Now I...

VS2012 Identifer not found when part of static lib

Using VS2012 C/C++: I created and linked a static lib called "libtools" to my project. Calls to functions in the libtools lib worked as expected. I created and linked a second static lib called "shunt" to my project. But when I incorporate a call to a function in shunt, I...

Set precision dynamically using sprintf

Using sprintf and the general syntax "%A.B" I can do this: double a = 0.0000005l; char myNumber[50]; sprintf(myNumber,"%.2lf",a); Can I set A and B dynamically in the format string?...

Passing int using char pointer in C

I'm trying to figure out how to pass an int using a char pointer. It fails once the int value is too large for the char. This is what I'm trying to figure out: char *args[5]; int i = 20; /*some other code/assignments*/ args[2] = (char *)&i; execv(path, args); How...

Identify that a string could be a datetime object

If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

How to read string until two consecutive spaces?

A well known function of the scanf() functions is that you can pass a format to scan input according to this format. For my case, I cannot seem to find a solution searching this and this documentation. I have a string (sInput) as the following: #something VAR1 this is a...

Is post-increment operator guaranteed to run instantly?

Let's say I have the following code: int i = 0; func(i++, i++); The increment is happening right after returning the value? Is it guaranteed that the first argument will be 0, and the second argument will be 1?...

execl() works on one of my code, but doesn't work on another

I already used execl() in code, and it worked well. But this time, I really have no idea why it doesn't work. So here's the code that do not work #include <unistd.h> #include <stdio.h> int main() { int i = 896; printf("please\n"); execl("home/ubuntu/server/LC/admin/admin", (char*)i, NULL); printf("i have no idea why\n");...

Algorithmic big o order of growth code

I'm doing an online course and i'm stuck on this question. I know there are similar questions but they don't help me. What is the order of growth of the worst case running time of the following code fragment as a function of N? int sum = 0; for (int...

C binary tree sort - extending it

I need some help in C Help me to extend the binary tree sort on C. I need to return a sorted array in sort function. here it is: #include <stdio.h> #include <stdlib.h> struct btreenode { struct btreenode *leftchild ; int data ; struct btreenode *rightchild ; } ; void...

scanf get multiple values at once

I need to get in one single shot different inputs from one single line. In particular I need to get a single char and then, depending on which char value I just read, it can be a string and an int or a string, an int and another string and...

Understanding Big-Ω (Big-Omega) notation

I was doing some reading on logarithms and the rate of growth of the running time of algorithms. I have, however, a problem understanding the Big-Ω (Big-Omega) notation. I know that we use it for 'asymptotic lower bounds', and that we can express the idea that an algorithm takes at...

Reverse ^ operator for decryption

I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...

getchar() not working in c

getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working. I am not able to figure out the root cause of the issue, can anyone please help me. #include<stdio.h> int...

Segmentation Fault if I don't say int i=0

void removeVowels(char* array){ int i,j,v; i=0; char vowel[]={'a','e','i','o','u'}; while(array[i]!='\0') { for(v=0;v<5;v++) { if (array[i]==vowel[v]) { j=i; while(array[j]!='\0') { array[j]=array[j+1]; j++; } i--; break; } } i++; } } in function removeVowels() if I don't include i=0; and just say int i; why does it give segmentation fault? Isn't it automatically...

Disconnect all vertices in a graph - Algorithm

I am looking for an algorithm that finds minimal subset of vertices such that by removing this subset (and edges connecting these vertices) from graph all other vertices become unconnected (i.e. the graph won't have any edges). Is there such algorithm? If not: Could you recommend some kind of heuristics...