📄 binary.h
字号:
/* cpplibga, free library of genetic algorithms. Copyright (C) 2003 Burger Y.A. (aka Jo Kruger) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USAContacts: address: planet Terra e-mail: jo_kruger@mail.ru kruger@selena.net.ua*/#ifndef __CPPLIBGA_GENOTYPE_BINARY_H__#define __CPPLIBGA_GENOTYPE_BINARY_H__#include <vector>#include <assert.h>#include <stdlib.h>#include <cpplibga/Types.h>namespace cpplibga{ namespace genotype { template<unsigned long bitNum> class Binary { public: typedef bool gene_type; static genotype_size_type size() {return bitNum;} Binary() : data(byteNum()) { assert(byteNum()); *data.rbegin()=0; } bool operator ==(const Binary& rhs) const { return data==rhs.data; } gene_type getGene(genotype_size_type locus) const { assert(locus<bitNum); genotype_size_type b=locus/8; return (data[b]>>(7-locus+b*8))&1; } virtual void setGene(genotype_size_type locus, gene_type value) { assert(locus<bitNum); genotype_size_type b=locus/8; genotype_size_type d=locus-b*8; data[b]=((data[b]|(1<<(7-d)))^(1<<(7-d)))|(((unsigned char)value)<<(7-d)); } virtual void invertGene(genotype_size_type locus) { assert(locus<bitNum); genotype_size_type b=locus/8; data[b]^=(1<<(7-locus+b*8)); } double unpackToDouble(genotype_size_type index, genotype_size_type size) const { double d=0; double base=1; for(genotype_size_type i=0; i<size; ++i) { if(getGene(index+i)) d+=base; base*=2; } return d; } virtual void fillRand() { for(genotype_size_type t=0; t<size(); ++t) { setGene(t,rand()<RAND_MAX/2); } } private: std::vector<unsigned char> data; static genotype_size_type byteNum() { return ((bitNum/8)+((bitNum-((bitNum/8)*8))>0?1:0)); } }; }}#endif
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -