2019年2月24日日曜日

開発環境

Modern C++チャレンジ ―C++17プログラミング力を鍛える100問 (Marius Bancila(著)、島 敏博(監修)、黒川 利明(翻訳)、オライリージャパン)の1章(数学の問題)、問題10(グレイコード)の解答を求めてみる。

コード

#include <iostream>
#include <bitset>
#include <cmath>

unsigned int encode(unsigned int n)
{
  return n ^ (n >> 1);
}
unsigned int decode(unsigned int n)
{
  unsigned int b = std::pow(2, 4);
  unsigned int m = b & n;
  while (b != 0)
  {
    unsigned int c = (b & m) >> 1;
    b >>= 1;
    m |= c ^ (n & b);
  }
  return m;
}
int main()
{
  for (unsigned int i = 0; i < std::pow(2, 5); i++)
  {
    unsigned int encoded = encode(i);
    unsigned int decoded = decode(encoded);
    if (i < 10)
    {
      std::cout << " ";
    }
    std::cout << i << " "
              << std::bitset<5>(i) << " "
              << std::bitset<5>(encoded) << " "
              << std::bitset<5>(decoded) << std::endl;
  }
}

入出力結果(cmd(コマンドプロンプト)、Terminal)

Active code page: 65001

C:\Users\...>cl /O2 sample10.cpp && sample10.exe
Microsoft(R) C/C++ Optimizing Compiler Version 19.16.27027.1 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

sample10.cpp
C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include\xlocale(319): warning C4530: C++ 例外処理を使っていますが、アンワインド セマンティクスは有効にはなりません。/EHsc を指定してください。
Microsoft (R) Incremental Linker Version 14.16.27027.1
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:sample10.exe
sample10.obj
 0 00000 00000 00000
 1 00001 00001 00001
 2 00010 00011 00010
 3 00011 00010 00011
 4 00100 00110 00100
 5 00101 00111 00101
 6 00110 00101 00110
 7 00111 00100 00111
 8 01000 01100 01000
 9 01001 01101 01001
10 01010 01111 01010
11 01011 01110 01011
12 01100 01010 01100
13 01101 01011 01101
14 01110 01001 01110
15 01111 01000 01111
16 10000 11000 10000
17 10001 11001 10001
18 10010 11011 10010
19 10011 11010 10011
20 10100 11110 10100
21 10101 11111 10101
22 10110 11101 10110
23 10111 11100 10111
24 11000 10100 11000
25 11001 10101 11001
26 11010 10111 11010
27 11011 10110 11011
28 11100 10010 11100
29 11101 10011 11101
30 11110 10001 11110
31 11111 10000 11111

C:\Users\...>

0 コメント:

コメントを投稿