10.4.4 agent解决方案模型的PBS(1)
分解1:如果您的猜测是正确且及时的,您就会在游戏中获胜。
分解2:如果猜测是由6字符编码组成且编码只包含字符(a~z,0~9)的组合,考虑到重复是允许的,而且该编码是我的agent递交给我的,则称猜测是正确的。
分解3:如果您的猜测是正确的,并且是在2分钟之内产生的,那么您的猜测是及时的。
分解4:如果有足够多的agent进行搜索,那么对编码进行穷举搜索将会成功。
分解5:N个agent足以在2分钟内从四百万个编码的样本中找到正确的编码。
分解6:如果编码每15秒改变一次,需要4N个代理2分钟内从四百万个编码的样本中找到正确的编码。
1. PBS的声明式实现
程序清单10-1遵从PBS的声明式语义。
程序清单10-1
- // Listing 10-1 A declarative implementation of the guess_it program.
-
- 1 #include "posix_process.h"
- 2 #include "posix_queue.h"
- 3 #include "valid_code.h"
- 4
- 5
- 6 char **av;
- 7 char **env;
- 8
- 9
- 10 int main(int argc,char *argv[],char *envp[])
- 11 {
- 12
- 13 valid_code ValidCode;
- 14 ValidCode.determination("ofind_code");
- 15 cout << (ValidCode() "you win" : "you lose)";
- 16 }
这样,在第13行声明了ValidCode谓词。这个谓词用来表示如下陈述:
- This is the code the trusted agent handed you.
在第14行,您通过调用谓词ValidCode( )来检测这个陈述。ValidCode( )谓词产生4个进程,每个进程又会依次产生两个线程。因此,实际上ValidCode( )谓词是使用并行编程(www.cppentry.com)来实现的。然而,它的实现被封装了起来。程序清单10-2显示了valid_code谓词类的声明。
程序清单10-2
- //Listing 10-2 Declaration of the valid_code predicate class.
-
-
- 1 #ifndef __VALID_CODE_H
- 2 #define __VALID_CODE_H
- 3 using namespace std;
- 4
- 5 #include <string>
- 6 class valid_code{
- 7 private:
- 8 string Code;
- 9 float TimeFrame;
- 10 string Determination;
- 11 bool InTime;
- 12 public:
- 13 bool operator()(void);
- 14 void determination(string X);
- 15 };
- 16
- 17 #endif
在C++(www.cppentry.com)中,谓词是有着返回布尔值的operator( )方法的类。应使用C++(www.cppentry.com)谓词来模拟PBS中谓词的概念。由于谓词是一个C++(www.cppentry.com)类,因此可以与容器及算法共同使用。程序清单10-3显示了谓词类的定义。
程序清单10-3
- // Listing 10-3 Definition of the valid_code predicate.
-
- 1 #include "valid_code.h"
- 2 #include "posix_process.h"
- 3 #include "posix_queue.h"
- 4
- 5 extern char **av;
- 6 extern char **env;
- 7
- 8
- 9 bool valid_code::operator()(void)
- 10 {
- 11 int Status;
- 12 int N;
- 13 string Result;
- 14 posix_process Child[4];
- 15 for(N = 0; N < 2; N++)
- 16 {
- 17 Child[N].binary(Determination);
- 18 Child[N].arguments(av);
- 19 Child[N].environment(env);
- 20 Child[N].run();
- 21 Child[N].pwait(Status);
- 22 }
- 23 posix_queue PosixQueue("queue_name");
- 24 PosixQueue.receive(Result);
- 25 if((Result == Code) && InTime){
- 26 return(true);
- 27 }
- 28 return(false);
- 29 }
- 30
- 31
- 32 void valid_code::determination(string X)
- 33 {
- 34 Determination = X;
- 35 }