现在的位置: 首页 > 综合 > 正文

遗传算法学习笔记(5)

2012年08月27日 ⁄ 综合 ⁄ 共 1923字 ⁄ 字号 评论关闭

赌轮算法学习

 

唉,逐步了解了遗传算法之后,发现之前想把这个用在游戏架构里面的想法或许是不能实现的,虽然遗传算法是一种框架形式的算法,但它毕竟是一个特定的算法,而且是有局限的算法,而不是一个通用的框架。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace Roulette
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();

int[] test = new int[] { 2,10,100, 23,150,220, 300, 400, 450 };


double[] probabilitys = RouletteWheel.GetProbability(test);

Random rand
= new Random();

int [] rest = new int[probabilitys.Length];

long start = DateTime.Now.Ticks;
int start1 = DateTime.Now.Millisecond;

for (int i = 0; i < 100000000; i++)
{
double te = rand.NextDouble();
int d = RouletteWheel.GetSelection(probabilitys, te);
switch (d)
{
case 0:
rest[
0]++;
break;
case 1:
rest[
1]++;
break;
case 2:
rest[
2]++;
break;
case 3:
rest[
3]++;
break;
case 4:
rest[
4]++;
break;
case 5:
rest[
5]++;
break;
case 6:
rest[
6]++;
break;
case 7:
rest[
7]++;
break;
case 8:
rest[
8]++;
break;
}
}

long elapsed = DateTime.Now.Ticks - start;
int elapsed1 = DateTime.Now.Millisecond - start1;
}



public class RouletteWheel
{

public static int GetSum(int[] _fitness)
{
int sum = 0;
int index =0;
foreach (int item in _fitness)
{
sum
+= _fitness[index++];
}
return sum;
}

public static int GetSelection(double[] _probabilitys,double _choise)
{
if(_choise>1.0 || _choise<0.0)
{
MessageBox.Show(
"Please Check Choise");
return -1;
}
int index = 0;
double cumulate = 0.0; //累积概率
while (index < _probabilitys.Length)
{
cumulate
+= _probabilitys[index];
if (_choise < cumulate)
{
return index;
}
index
++;
}

MessageBox.Show(
"Not Find This.");
return -1;
}

public static double GetSum(double[] _fitness)
{
double sum = 0;
int index = 0;
foreach (int item in _fitness)
{
sum
+= _fitness[index++];
}
return sum;
}

public static double[] GetProbability(int[] _fitness)
{
int sum = GetSum(_fitness);
double[] result = new double[_fitness.Length];
for (int i = 0; i < _fitness.Length; i++)
{
result[i]
= _fitness[i] / (double)sum;
}
return result;
}
}
}
}

 

抱歉!评论已关闭.