这次的人工智能布置了一个作业,就是用遗传算法求出y=x^2在x属于[1~511]之间的最大值。要用到随机数,二进制转换之类的功能。
所以就随手写了几个,方便需要的朋友拿去使用。
核心算法部分我删掉了。就提供我写的几个小函数,方便大家专注与核心代码的书写。
itoa是用来转换一个整数到二进制的
atoi是把二进制转化成整数的
getrand是用来获取随机初始种群的
getP是用来获取选择概率的
上代码
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 | /* Copyright (C) 2010 zerob13 <zerob13@gmail.com> */ #include <iostream> #include<time.h> #include<stdlib.h> #include<stdio.h> #include<string.h> using namespace std; #define MAXNUM 511;//种群范围 #define NUMLEN 8//种群编码长度 #define STNUM 6//种群个体数目 void itoa(int a,int ans[])//输入整数a,和数组ans,然后,a的二进制会存放在ans里。(当然你也可以直接用系统自带的itoa) { int i,j; int co=0; while(a!=1&&a){ ans[co++]=a%2; a/=2; } if(a) { ans[co++]=1; } for(i=0,j=NUMLEN-1;i<j;j--,i++) { ans[i]^=ans[j]; ans[j]^=ans[i]; ans[i]^=ans[j]; } } int atoi(int ans[])//输入二进制数组返回整数值 如数组ans[]={0,0,0,0,0,1,0,1},就会返回5 { int an=0,i; for(i=0;i<NUMLEN;i++) { an+=ans[i]*(1<<(7-i)); } return an; } void getrand(int ra[])//获取1~MAXNUM的随机初始种群 放在你输入的数组ra[]中 { srand(time(NULL)); for(int i=0;i<STNUM;i++) { ra[i]=1+rand()%MAXNUM; } } void getP(double P[]){//获取0~1随机数 放在你输入的数组P[]中,作为选择概率用 srand(time(NULL)); for(int i=0;i<STNUM;i++) { P[i]=double(rand()%10000)/10000.0; } } void _test_itoa(int ans[])//测试函数 { itoa(5,ans); for(int i=0;i<NUMLEN;i++) { printf("%d",ans[i]); } puts(""); } void _test_NUM(int ans[])//测试函数 { _test_itoa(ans); printf("%d\n",atoi(ans)); } void _test_rand(int ra[],double P[])//测试函数 { getrand(ra); getP(P); for(int i=0;i<STNUM;i++) { printf("%4d",ra[i]); } puts(""); for(int i=0;i<STNUM;i++) { printf("%lf ",P[i]); } puts(""); } int main (int argc, char * const argv[]) { int ans[NUMLEN]; int ra[STNUM]; double P[STNUM]; memset(ans,0,sizeof(ans)); _test_NUM(ans); _test_rand(ra,P); return 0; } |
