LoginSignup
2
2

More than 5 years have passed since last update.

ビットあみだくじなるものをDで解く

Posted at

問題はこんな感じらしいです
http://nabetani.sakura.ne.jp/hena/ord11bitamida/

解法は、

  1. 1を探す
  2. そこから右に0を探す
  3. 入れ替える
  4. 上記を各行について行う

とりあえず、簡単に

import std.algorithm,
       std.array,
       std.bitmanip,
       std.conv,
       std.format,
       std.stdio;

void main()
{
    /*0*/ test( "d6-7b-e1-9e", "740631825" );
    /// その他のテストケースは省略
}


void test(string input, string desired)
{
    if(bitLadderLottery(input) != desired)
        throw new Exception("Error case of: " ~ input);
}


string bitLadderLottery(string input)
{
    uint[4] crossBit;
    input.formattedRead("%x-%x-%x-%x", &(crossBit[0]), &(crossBit[1]), &(crossBit[2]), &(crossBit[3]));

    uint[9] numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];
    foreach(e; crossBit[])
        swapNumbers(numbers, e);

    auto writer = appender!string();
    writer.formattedWrite("%(%s%)", numbers[]);
    return writer.data;
}

unittest{
    assert(bitLadderLottery("d6-7b-e1-9e") == "740631825");
}


void swapNumbers(ref uint[9] numbers, uint crossLine)
{
    BitArray bitarr;
    bitarr.init((cast(void*)&crossLine)[0 .. 1], 8);
    bitarr.reverse;

    foreach(ref i; 0 .. 8)
    {
        if(!bitarr[i])
            continue;

        size_t nextZeroIndex = i;
        while(bitarr[nextZeroIndex] && nextZeroIndex < 8)
            ++nextZeroIndex;

        swap(numbers[i], numbers[nextZeroIndex]);
        i = nextZeroIndex;
    }
}
unittest{
    uint[9] numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8];

    swapNumbers(numbers, cast(uint)(0xd6));
    assert(numbers == [2, 1, 0, 4, 3, 7, 6, 5, 8]);
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2