This repository was archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnQueensWorker.h
109 lines (78 loc) · 2.37 KB
/
nQueensWorker.h
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
//
// nQueensWorker.h
//
#ifndef WORKER_NQUEENS_H
#define WORKER_NQUEENS_H
#include <vector>
using namespace std;
#include "MWWorker.h"
#include "nQueensTask.h"
template <class CommType>
class nQueensTask;
template <class CommType>
class nQueensWorker : public MWWorker<CommType>
{
friend class nQueensTask<CommType>;
public:
nQueensWorker(CommType* RMC_)
: MWWorker<CommType>(RMC_), N(-1)
{ task = new nQueensTask<CommType>(0,RMC_); }
MWReturn unpack_init_data( void )
{
RMC->unpack ( &N, 1 );
RMC->unpack ( &partition_factor, 1 );
return OK;
}
void execute_task( MWTask<CommType> * );
void search_subspace ( vector<int>& perm, int N, int givenPerm, vector<int>&res );
void isCorrectPermutation ( vector<int>& perm, int N, vector<int>& res );
protected:
int N;
int partition_factor;
};
template <class CommType>
void nQueensWorker<CommType>::execute_task( MWTask<CommType> *t )
{
MWprintf(1,"nqueens info: N=%d, pfact=%d\n", N,partition_factor);
vector<int> permutation(N);
int givenPerm = partition_factor >= N ? 0 : N - partition_factor;
nQueensTask<CommType> *tf = (nQueensTask<CommType> *) t;
int index = tf->num;
MWprintf(1,"nqueens info: tf=%d index=%d\n", tf, index);
for (int i = 0; i < givenPerm; i++ ) {
permutation[i] = index % N;
index = index / N;
}
search_subspace ( permutation, N, givenPerm,tf->results );
MWprintf(1,"nqueens execute_task finishes\n");
}
template <class CommType>
void nQueensWorker<CommType>::search_subspace ( vector<int>& permutation, int N, int givenPerm, vector<int>& res )
{
MWprintf(1,"nqueens search_subspace N=%d givenPerm=%d\n",N, givenPerm);
if ( givenPerm == N )
return isCorrectPermutation ( permutation, N, res );
for ( int i = 0; i < N; i++ ) {
permutation[givenPerm] = i;
search_subspace ( permutation, N, givenPerm + 1, res );
if (res.size() > 0) return;
}
}
template <class CommType>
void nQueensWorker<CommType>::isCorrectPermutation ( vector<int>& permutation, int N, vector<int>& res )
{
MWprintf(1,"nqueens isCorrectPermutation\n");
for (int i = 0; i < N; i++ ) {
for (int j = 0; j < N; j++ ) {
if ( i == j ) continue;
if ( permutation[i] == permutation[j] )
return;
if ( permutation[i] + ( j - i ) == permutation[j] )
return;
}
}
MWprintf(1,"nqueens copying result\n");
for (int i = 0; i < N; i++ )
res[i] = permutation[i];
}
#endif