Cannot add two equality constraints to nlopt - nlopt

I am using nlopt in C, and I would like to add a set of vector equality constraint and a single equality constraint. Here is a sample of my code:
nlopt_opt opt;
opt = nlopt_create(NLOPT_GN_ISRES, (P.N));
nlopt_set_upper_bounds(opt, ub);
nlopt_set_lower_bounds(opt, lb);
nlopt_set_min_objective(opt, F, &P);
printf("\nAdding constraint_A: %d", nlopt_add_equality_mconstraint(opt, (P.N), constraint_A, &P, mtol_c));
printf("\nAdding constraint_B: %d", nlopt_add_equality_constraint(opt, constraint_B, &P, tol_c));
Constraints A and B are defined as follows:
void constraint_A(unsigned Q, double* result, unsigned N, const double *x, double *grad, void *data){
param *p = (param*)data;
unsigned int i, j;
if (grad) {
for(i=0; i<((*p).N); i++){
for(j=0; j<((*p).N); j++){
grad[((*p).N)*i+j] = ((*p).dx)*((*p).q)[((*p).N)*i+j] / ((*p).r)[i];
}
}
}
for(i=0; i<((*p).N); i++){
for(result[i]=0.0, j=0; j<((*p).N); j++){
result[i] += x[j]*((*p).q)[((*p).N)*i+j];
}
result[i] = ( ((*p).dx)*result[i]-((*p).r)[i] ) / ((*p).r)[i];
}
}
double constraint_B(unsigned N, const double *x, double *grad, void *data){
param *p = (param*)data;
double result;
unsigned int i;
if(grad){
for(i=0; i<((*p).N); i++){
grad[i] = ((*p).dx)*gsl_pow_2(((*p).x)[i]);
}
}
for(result=0.0, i=0; i<((*p).N); i++){
result += x[i]*gsl_pow_2(((*p).x)[i]);
}
result = ((*p).dx)*result-1.0;
return result;
}
where dx, q, r and x are elements of the data structure P.
I obtain the output
Adding constraint_A: 1
Adding constraint_B: -2
If I reverse the order of the operations as follows
printf("\nAdding constraint_B: %d", nlopt_add_equality_constraint(opt, constraint_B, &P, tol_c));
printf("\nAdding constraint_A: %d", nlopt_add_equality_mconstraint(opt, (P.N), constraint_A, &P, mtol_c));
I still obtain
Adding constraint_B: 1
Adding constraint_A: -2
Whenever the return code for one constraint is negative, the constraint is ignored in the optimization.
Why is the constraint return code negative? Are the two constraint inconsistent with each other?

Related

Hi, I wrote code in C++ fot linear search but it displays the index of searched elemet twice with second index value as random garbage value

Here is the code.what i did is implement linear search on some elements of the array and the push searched elements in stack,afterwards I print the popped elements from stack and print them.But in search function it displays two index values.
using namespace std;
int searched[10];
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
int main(void)
{
int arr[15] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
int x = 0;
for(int i=0;i<8;i++)
{
x++;
int result = search(arr, n, x);
cout << "searched Element is " << result<<"\t\t";
push(result);
pop();
}
return 0;
}```
There are two issues that lead to this confusing result.
First, if I am not mistaken the search function, which was written like this:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
is parsed similarly to the following:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
cout<<"The element is found at the index"<<i<<"\n\n";
}
}
return x;
}
Presumably you meant this:
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++) {
if (arr[i] == x) {
cout<<"The element is found at the index"<<i<<"\n\n";
return x;
}
}
}
Second, since the global n starts at the value 100, the search loop runs off the end of the length 15 array, into other memory. This is probably undefined behavior.

Longest length of valid parenthesis problem

I got stuck on this problem of finding the length of the longest valid parenthesis substring which either contains '(' or ')' . Actually there are many methods to solve this problem but i tried to go with finding the longest common substring (LCS) of the two strings..
I am getting the runtime error....
Line 1061: Char 9: runtime error: addition of unsigned offset to 0x7ffd2d443260 overflowed to 0x7ffd2d44325f (basic_string.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/basic_string.h:1070:9
Please check what is wrong in this....
class Solution {
public:
int LCS(string s1,string s2)
{
int m = s1.length();
int n = s2.length();
int dp[m+1][n+1];
memset(dp,0,sizeof(dp));
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
dp[i][j] = 0;
}
int res = 0;
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
{
if(i==j)
dp[i][j] = 0;
else if(s1[i-1]==s2[j-1]){
dp[i][j] = 1 + dp[i-1][j-1];
res = max(res,dp[i][j]);
}
else
dp[i][j] = 0;
}
}
return res;
}
int longestValidParentheses(string s) {
// here we can find the longest LCS..
if(s.length()==0 || s.length()==1)
return 0;
string str = "";
for(int i=s.length()-1;i>=0;i--)
{
if(s[i]==')')
str += '(';
else if(s[i]=='(')
str += ')';
}
int res = LCS(s,str);
return res;
}
};

how can I display unsigned char with SetWindowText

I want to display unsigned char value with SetWindowText, but nothing displayed on label
code
DWORD WINAPI fill_matrix(LPVOID lpParameter)
{
unsigned char a = 'h';
for (int i = 0; i < 8; i++){
for (int j = 0; j <8; j++)
{
SetWindowText(hWndLabel[i * 8 + j], (LPCTSTR)a);
}
}
return 0;
}
I configured my project proprieties with unicode
SetWindowText requires string, not a single charater.
You should use SetWindowTextA, which explicitly use ANSI characters.
Fixed code:
DWORD WINAPI fill_matrix(LPVOID lpParameter)
{
unsigned char a = 'h';
for (int i = 0; i < 8; i++){
for (int j = 0; j <8; j++)
{
char window_text[2] = {a, '\0'};
SetWindowTextA(hWndLabel[i * 8 + j], window_text);
}
}
return 0;
}

Merge multiple input strings to sort alphabetically

Help! Here I have a program, that sorts input strings alphabetically. The problem is that it sorts the entered strings seperately, but I need them merged and sorted together. What am i doing wrong?
int main (void)
{
char repeat;
do{
char string[128], string1[128], temp;
int n, i, j;
cout<<"\nEnter symbols: "<<endl;
gets(string);
n = strlen(string);
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
int s = tolower(string[i]) - tolower(string[j]);
if ( s == 0 )
{
s = string[i] - string[j];
}
if (s > 0)
{
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
cout<<"\nSorted alphabetically: "<<endl;
printf("\n%s", string);
printf("\n");
cout<<"\nEnter more symbols: "<<endl;
gets(string1);
n = strlen(string1);
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
int s = tolower(string1[i]) - tolower(string1[j]);
if ( s == 0 )
{
s = string1[i] - string1[j];
}
if (s > 0)
{
temp = string1[i];
string1[i] = string1[j];
string1[j] = temp;
}
}
}
cout<<"\nSorted alphabetically: "<<endl;
the function below merges the strings, when they both have been already sorted
strcat(string, string1);
printf(\n%s", string);
printf("\n");
cout << "To repeat press j" << endl;
cin >> repeat;
}
while ( repeat == 'j' );
system("Pause");
return 0;
}
The easiest way is to merge the strings into a new one.
int main (void)
{
char repeat;
do{
char string[128], string1[128],string2[256], temp;
int n, i, j;
cout<<"\nEnter symbols: "<<endl;
gets(string);
cout<<"\nEnter more symbols: "<<endl;
gets(string1);
strcpy (string2,string);
strcat (string2,string1);
// rest of your code here. You only need to sort string2

How to parallelize Sudoku solver using Grand Central Dispatch?

As a programming exercise, I just finished writing a Sudoku solver that uses the backtracking algorithm (see Wikipedia for a simple example written in C).
To take this a step further, I would like to use Snow Leopard's GCD to parallelize this so that it runs on all of my machine's cores. Can someone give me pointers on how I should go about doing this and what code changes I should make? Thanks!
Matt
Please let me know if you end up using it. It is run of the mill ANSI C, so should run on everything. See other post for usage.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
short sudoku[9][9];
unsigned long long cubeSolutions=0;
void* cubeValues[10];
const unsigned char oneLookup[64] = {0x8b, 0x80, 0, 0x80, 0, 0, 0, 0x80, 0, 0,0,0,0,0,0, 0x80, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ifOne(int val) {
if ( oneLookup[(val-1) >> 3] & (1 << ((val-1) & 0x7)) )
return val;
return 0;
}
void init_sudoku() {
int i,j;
for (i=0; i<9; i++)
for (j=0; j<9; j++)
sudoku[i][j]=0x1ff;
}
void set_sudoku( char* initialValues) {
int i;
if ( strlen (initialValues) != 81 ) {
printf("Error: inputString should have length=81, length is %2.2d\n", strlen(initialValues) );
exit (-12);
}
for (i=0; i < 81; i++)
if ((initialValues[i] > 0x30) && (initialValues[i] <= 0x3a))
sudoku[i/9][i%9] = 1 << (initialValues[i] - 0x31) ;
}
void print_sudoku ( int style ) {
int i, j, k;
for (i=0; i < 9; i++) {
for (j=0; j < 9; j++) {
if ( ifOne(sudoku[i][j]) || !style) {
for (k=0; k < 9; k++)
if (sudoku[i][j] & 1<<k)
printf("%d", k+1);
} else
printf("*");
if ( !((j+1)%3) )
printf("\t");
else
printf(",");
}
printf("\n");
if (!((i+1) % 3) )
printf("\n");
}
}
void print_HTML_sudoku () {
int i, j, k, l, m;
printf("<TABLE>\n");
for (i=0; i<3; i++) {
printf(" <TR>\n");
for (j=0; j<3; j++) {
printf(" <TD><TABLE>\n");
for (l=0; l<3; l++) { printf(" <TR>"); for (m=0; m<3; m++) { printf("<TD>"); for (k=0; k < 9; k++) { if (sudoku[i*3+l][j*3+m] & 1<<k)
printf("%d", k+1);
}
printf("</TD>");
}
printf("</TR>\n");
}
printf(" </TABLE></TD>\n");
}
printf(" </TR>\n");
}
printf("</TABLE>");
}
int doRow () {
int count=0, new_value, row_value, i, j;
for (i=0; i<9; i++) {
row_value=0x1ff;
for (j=0; j<9; j++)
row_value&=~ifOne(sudoku[i][j]);
for (j=0; j<9; j++) {
new_value=sudoku[i][j] & row_value;
if (new_value && (new_value != sudoku[i][j]) ) {
count++;
sudoku[i][j] = new_value;
}
}
}
return count;
}
int doCol () {
int count=0, new_value, col_value, i, j;
for (i=0; i<9; i++) {
col_value=0x1ff;
for (j=0; j<9; j++)
col_value&=~ifOne(sudoku[j][i]);
for (j=0; j<9; j++) {
new_value=sudoku[j][i] & col_value;
if (new_value && (new_value != sudoku[j][i]) ) {
count++;
sudoku[j][i] = new_value;
}
}
}
return count;
}
int doCube () {
int count=0, new_value, cube_value, i, j, l, m;
for (i=0; i<3; i++)
for (j=0; j<3; j++) {
cube_value=0x1ff;
for (l=0; l<3; l++)
for (m=0; m<3; m++)
cube_value&=~ifOne(sudoku[i*3+l][j*3+m]);
for (l=0; l<3; l++)
for (m=0; m<3; m++) {
new_value=sudoku[i*3+l][j*3+m] & cube_value;
if (new_value && (new_value != sudoku[i*3+l][j*3+m]) ) {
count++;
sudoku[i*3+l][j*3+m] = new_value;
}
}
}
return count;
}
#define FALSE -1
#define TRUE 1
#define INCOMPLETE 0
int validCube () {
int i, j, l, m, r, c;
int pigeon;
int solved=TRUE;
//check horizontal
for (i=0; i<9; i++) {
pigeon=0;
for (j=0; j<9; j++)
if (ifOne(sudoku[i][j])) {
if (pigeon & sudoku[i][j]) return FALSE;
pigeon |= sudoku[i][j];
} else {
solved=INCOMPLETE;
}
}
//check vertical
for (i=0; i<9; i++) {
pigeon=0;
for (j=0; j<9; j++)
if (ifOne(sudoku[j][i])) {
if (pigeon & sudoku[j][i]) return FALSE;
pigeon |= sudoku[j][i];
}
else {
solved=INCOMPLETE;
}
}
//check cube
for (i=0; i<3; i++)
for (j=0; j<3; j++) {
pigeon=0;
r=j*3; c=i*3;
for (l=0; l<3; l++)
for (m=0; m<3; m++)
if (ifOne(sudoku[r+l][c+m])) {
if (pigeon & sudoku[r+l][c+m]) return FALSE;
pigeon |= sudoku[r+l][c+m];
}
else {
solved=INCOMPLETE;
}
}
return solved;
}
int solveSudoku(int position ) {
int status, i, k;
short oldCube[9][9];
for (i=position; i < 81; i++) {
while ( doCube() + doRow() + doCol() );
status = validCube() ;
if ((status == TRUE) || (status == FALSE))
return status;
if ((status == INCOMPLETE) && !ifOne(sudoku[i/9][i%9]) ) {
memcpy( &oldCube, &sudoku, sizeof(short) * 81) ;
for (k=0; k < 9; k++) {
if ( sudoku[i/9][i%9] & (1<<k) ) {
sudoku[i/9][i%9] = 1 << k ;
if (solveSudoku(i+1) == TRUE ) {
/* return TRUE; */
/* Or look for entire set of solutions */
if (cubeSolutions < 10) {
cubeValues[cubeSolutions] = malloc ( sizeof(short) * 81 ) ;
memcpy( cubeValues[cubeSolutions], &sudoku, sizeof(short) * 81) ;
}
cubeSolutions++;
if ((cubeSolutions & 0x3ffff) == 0x3ffff ) {
printf ("cubeSolutions = %llx\n", cubeSolutions+1 );
}
//if ( cubeSolutions > 10 )
// return TRUE;
}
memcpy( &sudoku, &oldCube, sizeof(short) * 81) ;
}
if (k==8)
return FALSE;
}
}
}
return FALSE;
}
int main ( int argc, char** argv) {
int i;
if (argc != 2) {
printf("Error: number of arguments on command line is incorrect\n");
exit (-12);
}
init_sudoku();
set_sudoku(argv[1]);
printf("[----------------------- Input Data ------------------------]\n\n");
print_sudoku(1);
solveSudoku(0);
if ((validCube()==1) && !cubeSolutions) {
// If sudoku is effectively already solved, cubeSolutions will not be set
printf ("\n This is a trivial sudoku. \n\n");
print_sudoku(1);
}
if (!cubeSolutions && validCube()!=1)
printf("Not Solvable\n");
if (cubeSolutions > 1) {
if (cubeSolutions >= 10)
printf("10+ Solutions, returning first 10 (%lld) [%llx] \n", cubeSolutions, cubeSolutions);
else
printf("%llx Solutions. \n", cubeSolutions);
}
for (i=0; (i < cubeSolutions) && (i < 10); i++) {
memcpy ( &sudoku, cubeValues[i], sizeof(short) * 81 );
printf("[----------------------- Solution %2.2d ------------------------]\n\n", i+1);
print_sudoku(0);
//print_HTML_sudoku();
}
return 0;
}
For one, since backtracking is a depth-first search it is not directly parallelizable, since any newly computed result cannot be used be directly used by another thread. Instead, you must divide the problem early, i.e. thread #1 starts with the first combination for a node in the backtracking graph, and proceeds to search the rest of that subgraph. Thread #2 starts with the second possible combination at the first and so forth. In short, for n threads find the n possible combinations on the top level of the search space (do not "forward-track"), then assign these n starting points to n threads.
However I think the idea is fundamentally flawed: Many sudoku permutations are solved in a matter of a couple thousands of forward+backtracking steps, and are solved within milliseconds on a single thread. This is in fact so fast that even the small coordination required for a few threads (assume that n threads reduce computation time to 1/n of original time) on a multi-core/multi-CPU is not negligible compared to the total running time, thus it is not by any chance a more efficient solution.
Are you sure you want to do that? Like, what problem are you trying to solve? If you want to use all cores, use threads. If you want a fast sudoku solver, I can give you one I wrote, see output below. If you want to make work for yourself, go ahead and use GCD ;).
Update:
I don't think GCD is bad, it just isn't terribly relevant to the task of solving sudoku. GCD is a technology to tie GUI events to code. Essentially, GCD solves two problems, a Quirk in how the MacOS X updates windows, and, it provides an improved method (as compared to threads) of tying code to GUI events.
It doesn't apply to this problem because Sudoku can be solved significantly faster than a person can think (in my humble opinion). That being said, if your goal was to solve Sudoku faster, you would want to use threads, because you would want to directly use more than one processor.
[bear#bear scripts]$ time ./a.out ..1..4.......6.3.5...9.....8.....7.3.......285...7.6..3...8...6..92......4...1...
[----------------------- Input Data ------------------------]
*,*,1 *,*,4 *,*,*
*,*,* *,6,* 3,*,5
*,*,* 9,*,* *,*,*
8,*,* *,*,* 7,*,3
*,*,* *,*,* *,2,8
5,*,* *,7,* 6,*,*
3,*,* *,8,* *,*,6
*,*,9 2,*,* *,*,*
*,4,* *,*,1 *,*,*
[----------------------- Solution 01 ------------------------]
7,6,1 3,5,4 2,8,9
2,9,8 1,6,7 3,4,5
4,5,3 9,2,8 1,6,7
8,1,2 6,4,9 7,5,3
9,7,6 5,1,3 4,2,8
5,3,4 8,7,2 6,9,1
3,2,7 4,8,5 9,1,6
1,8,9 2,3,6 5,7,4
6,4,5 7,9,1 8,3,2
real 0m0.044s
user 0m0.041s
sys 0m0.001s

Resources