Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

c++ - Flip 4x4 bit-grid horizontally/vertically/diagonally

I am programming a board game with ab board of 4x4 squares and use a unsigned short to save whether a stone is on each square. 0 := empty square and 1 := stone on square

A board with 8 stones like this:

1111
0000
0101
1010

is saved line by line like this:

unsigned short board = 0b1111000001011010 // = 61530

I need to flip the board vertically,horizontally and diagonally.

Example:

Vertically Horizontally Diagonally
1010
0101
0000
1111
1111
0000
1010
0101
1001
1010
1001
1010
0b1010010100001111 //= 42255 0b1111000010100101 //= 61605 0b1001101010011010 //= 39578

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All three operations can be expressed using bitwise operations like this:

uint16_t vert_flip_board(uint16_t x) {
    return ((x & 0b0000'0000'0000'1111) << 12) |
           ((x & 0b0000'0000'1111'0000) <<  4) |
           ((x & 0b0000'1111'0000'0000) >>  4) |
           ((x & 0b1111'0000'0000'0000) >> 12);
}

uint16_t horiz_flip_board(uint16_t x) {
    return ((x & 0b0001'0001'0001'0001) << 3) |
           ((x & 0b0010'0010'0010'0010) << 1) |
           ((x & 0b0100'0100'0100'0100) >> 1) |
           ((x & 0b1000'1000'1000'1000) >> 3);
}

uint16_t transpose_board(uint16_t x) {
    return  // Main diagonal.
            (x & 0b1000'0100'0010'0001) |
           // Upper diagonals.
           ((x & 0b0100'0010'0001'0000) >> 3) |
           ((x & 0b0010'0001'0000'0000) >> 6) |
           ((x & 0b0001'0000'0000'0000) >> 9) |
           // Lower diagonals.
           ((x & 0b0000'1000'0100'0010) << 3) |
           ((x & 0b0000'0000'1000'0100) << 6) |
           ((x & 0b0000'0000'0000'1000) << 9);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...