繁体   English   中英

快速Toffoli门实施

[英]Fast Toffoli Gate Implementation

我正在研究一种使用toffoli门进行遗传算法的课程。 我已经有了遗传算法,但它很慢。

评估功能每个“有机体”运行〜10,000次toffoli门功能。 人口为1,000,每代运行超过100,000次。 它是我遗传算法中最慢的部分。

对于我的实现, Toffoli Gate作用于位串。 每个位的状态为None,On,Off或Flip。 每个字符串只有一位可以具有FLIP状态。 如果状态为ON的所有位都为1,并且所有设置为OFF的位都为0,则toffoli门将设置为FLIP的位翻转,忽略None位。

例如

X = FLIP
@ = ON
O = OFF
- = NONE

然后输入“1001”和“X0- @”的toffoli门看起来像

1001
XO-@
----
0001

实现这一目标的快速方法是什么?

我的初始实现使用bitsets。

#define BITLEN 10
#define INPUT std::bitset<BITLEN>
#define GATE std::bitset<BITLEN*2>

void toffoli(const GATE* gate, INPUT* state) {
    bool all_conditions = true;
    int flip_index = -1;
    bool set = false;
    for (int i = 0; i < BITLEN; i++) {
        /*a0 and a1 represent the state of A
          11 is FLIP, 10 is ON, 01 is OFF, and 00 is NONE */
        bool A = (*state)[i];
        bool a1 = (*gate)[i*2];
        bool a0 = (*gate)[(i*2)+1];

        if (a1&&a0) {
            flip_index = i;
            set = true;
        }

        //NONE or FLIP have no condition to meet
        //ON means A must be true
        //OFF means A must be false
        //this simplifies to the below if statement
        if (!((!a0&&!a1) || (!A&&a1) || (A&&a0))) {
            all_conditions = false;
            break;
        }
    }

    //if all conditions are met flip the bit with state FLIP
    //check set flag in case gate is not valid
    if (all_conditions && set)
        state->flip(flip_index);
}

更改您的门代表:

struct GATE {
    std::bitset<BITLEN> required_on;
    std::bitset<BITLEN> required_off;
    std::bitset<BITLEN> flip;
};

然后,您可以通过位操作非常有效地实现操作:

void toffoli(const GATE* gate, INPUT* state) {
    if((*state & (gate->required_on | gate->required_off)) == gate->required_on)
        *state ^= gate->flip;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM