二元变量的置换及其值表

Permutation of binary variables and their value table

本文关键字:二元 变量      更新时间:2023-10-16

我有一些布尔变量,并希望以相同的"顺序"更改值表

for example: 2^2 = 4 combinations
0,0 = A
0,1 = B
1,0 = C
1,1 = D
Now I swap x_1 with x_2 and end up with
0,0 = A
0,1 = C
1,0 = B
1,1 = D

我正在寻找一个函数,返回值表"排序"。给定值的排列顺序。

一种方法是循环遍历所有比特的组合并将它们转换为排列状态。但是我如何在c++中做到这一点?

例如

如果我的顺序是(3,2,1)那么x_1,x_2_x_3 = 0,1,1就会排列到1,1,0所以

sorted_table[sort(0,1,1)] = sorted_table[6] = old_table[3]

有什么办法可以快速完成吗?我想我可以处理一些二进制向量,但这似乎很慢?

存储变量列表,然后根据自定义比较操作符对它们进行排序。例如:

     // Ordering
    int* _ordering;
    // Variable
    template<size_t T> 
    class Variable : public bitset<T> {
    private:
      char*      _name;                // A variable has a name.
    public:
      // Constructors
      Variable()
        :bitset<T>(),          _name(NULL) {};
      Variable(string bitstring, char* name)
        :bitset<T>(bitstring), _name(name) {};
      // Name accessor
      char*& name(void) {return _name;};
      // Comparison operator
      bool operator<(const Variable<T> &rhs) const {
        for (int oidx=0; oidx<T; oidx++) 
          if (bitset<T>::test(_ordering[oidx])) { 
            if (!rhs.test(_ordering[oidx])) 
              // Left is bigger.
              return false;
          } else 
            if (rhs.test(_ordering[oidx])) 
              // Right is bigger.
              return true;
        // They match at all values.
        return false;   
      }
    };

下面是一个快速而肮脏的主程序,它用8个值的变量来测试。

    #include <iostream>
    #include <bitset>
    #include <stdlib.h>
    #include <stdio.h>
    #include <vector>
    #include <algorithm>
    ...
    #define BITS 8
    int main(int argc, char* argv[]) {
      int i;
      // Create the ordering based on the command line arguments
      _ordering = new int[BITS];
      for (i=0; i<BITS; i++) _ordering[i] = atoi(argv[i+1]);
      // Read in each variable
      int size=(argc-BITS-1)/2;
      vector< Variable<BITS> > variables;
      for (i=0; i<size*2; i+=2) {
        cout << "Creating bitset " << argv[BITS+1+i]<<":"<<argv[BITS+2+i]<<endl;
        variables.push_back(Variable<BITS>(string(argv[BITS+i+1]), argv[BITS+i+2]));
      }
      // Display the variables
      for (i=0; i<variables.size(); i++) 
        cout << variables[i] << ":" << variables[i].name() << endl;
      // Sort them
      cout << endl << "Sorting..." << endl;
      sort(variables.begin(), variables.end());
      // Display again
      for (i=0; i<variables.size(); i++) 
        cout << variables[i] << ":" << variables[i].name() << endl;
    }

输出如下:

$ ./bitsort 0 1 2 3 4 5 6 7  01 a 11 b 10 c 00 d
Creating bitset 01:a
Creating bitset 11:b
Creating bitset 10:c
Creating bitset 00:d
00000001:a
00000011:b
00000010:c
00000000:d
Sorting...
00000000:d
00000010:c
00000001:a
00000011:b