-rw-r--r-- 1281 cryptattacktester-20231020/weighttest.cpp raw
#include <cassert>
#include <iostream>
#include "random.h"
#include "bit_vector.h"
#include "index.h"
#include "index_cost.h"
#include "bit_vector_cost.h"
using namespace std;
int main()
{
  for (bigint n = 0;n <= 128;++n) {
    cout << "weighttest " << n << '\n' << flush;
    for (bigint loop = 0;loop < 256;++loop) {
      vector<bit> x;
      for (bigint k = 0;k < n;++k)
        x.push_back(bit(random_bool()));
      bigint ops = bit::ops();
      auto w = bit_vector_hamming_weight(x);
      assert(bit::ops()-ops == bit_vector_hamming_weight_cost(n));
      if (n == 0)
        assert(w.size() == 0);
      else
        assert(w.size() == nbits(n));
      bigint wvalue = 0;
      for (bigint k = 0;k < w.size();++k)
        wvalue += ((bigint) w.at(k).value()) << k;
      bigint xsum = 0;
      for (bigint k = 0;k < x.size();++k)
        xsum += x.at(k).value();
      assert(wvalue == xsum);
      if (loop < 4) {
        for (bigint target = 0;nbits(target) <= w.size();++target) {
          bigint ops = bit::ops();
          auto wisnot = bit_vector_hamming_weight_isnot(x,target);
          assert(bit::ops()-ops == bit_vector_hamming_weight_isnot_cost(n,target));
          assert(wisnot.value() == (xsum != target));
        }
      }
    }
  }
  return 0;
}