- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
#include <stdio.h>
#include <inttypes.h>
#include <stddef.h>
void printuint64(const uint64_t state);
uint64_t game_of_life8x8(const uint64_t old);
uint8_t getbit(uint64_t in, uint8_t y, uint8_t x);
uint8_t getbit(uint64_t in, uint8_t y, uint8_t x)
{
return !!((in) & (1ULL << ((y&0b111) + (x&0b111)*8)) );
}
uint64_t setbit(uint8_t y, uint8_t x, uint8_t bit)
{
if (bit)
{
return 1ULL << ((y&0b111) + (x&0b111)*8);
}
return 0;
}
uint64_t game_of_life8x8(const uint64_t old)
{
uint64_t new_state = 0;
#define GETBIT(y,x,val) getbit(val, y, x)
#define SETBIT(y,x,bit) setbit(y,x,bit)
#define SUMAROUND(y,x,val) ( \
GETBIT(y+1,x,val) + GETBIT(y-1,x,val) \
+ GETBIT(y,x+1,val) + GETBIT(y,x-1,val) \
+ GETBIT(y+1,x+1,val) + GETBIT(y+1,x-1,val) \
+ GETBIT(y-1,x+1,val) + GETBIT(y-1,x-1,val) \
)
#define CELLSTATE(y,x,val) \
(GETBIT(y,x,old) == 1 ? \
( ((SUMAROUND(y,x,val) == 2 ) || ( SUMAROUND(y,x,val) == 3 )) ? 1 : 0) \
: \
( ( SUMAROUND(y,x,val) == 3 ) ? 1 : 0 ) \
)
#define SETCELL_SH(y,x,val) SETBIT(y,x,CELLSTATE(y,x,val))
#define FILL_LINE(y) \
SETCELL_SH(y,7,old) | SETCELL_SH(y,6,old) | SETCELL_SH(y,5,old) | \
SETCELL_SH(y,4,old) | SETCELL_SH(y,3,old) | SETCELL_SH(y,2,old) | \
SETCELL_SH(y,1,old) | SETCELL_SH(y,0,old)
new_state = FILL_LINE(7) | FILL_LINE(6) | FILL_LINE(5)
| FILL_LINE(4) | FILL_LINE(3) | FILL_LINE(2)
| FILL_LINE(1) | FILL_LINE(0);
return new_state;
}
void printuint64(const uint64_t state)
{
for (size_t i = 7; i != SIZE_MAX; i--)
{
for (size_t j = 7; j != SIZE_MAX; j--)
{
printf("%u", !!((state >> (j+i*8)) & 1) );
}
printf("\n");
}
}
int main(void)
{
// Glider
uint64_t state =
(( 0b01000000ULL ) << 8*7 ) |
(( 0b00100000ULL ) << 8*6 ) |
(( 0b11100000ULL ) << 8*5 ) |
(( 0b00000000ULL ) << 8*4 ) |
(( 0b00000000ULL ) << 8*3 ) |
(( 0b00000000ULL ) << 8*2 ) |
(( 0b00000000ULL ) << 8*1 ) |
(( 0b00000000ULL ) << 8*0 );
for (size_t i = 0; i < 50; i++)
{
printuint64(state);
state = game_of_life8x8(state);
printf("\n");
}
return 0;
}
Conway's game of life внутри uint64_t (8 на 8) с периодическими граничными условиями.