fork download
  1. #include <cstring> // For memset
  2.  
  3. struct Automata1D
  4. {
  5. Automata1D(unsigned int _rule = 22, unsigned int _width = 80)
  6. : mRule(_rule)
  7. , mWidth(_width)
  8. , mGeneration(0)
  9. {
  10. mValues[0] = new char[mWidth];
  11. mValues[1] = new char[mWidth];
  12.  
  13. memset(mValues[0], 0, mWidth);
  14. memset(mValues[1], 0, mWidth);
  15. }
  16.  
  17. ~Automata1D()
  18. {
  19. delete mValues[1];
  20. delete mValues[0];
  21. }
  22.  
  23. void evolve()
  24. {
  25. int lastGeneration = mGeneration % 2;
  26. int thisGeneration = ++mGeneration % 2;
  27.  
  28. for (unsigned int i = 0; i < mWidth; ++i) {
  29. int leftVal = (mValues[lastGeneration][((i - 1) + mWidth) % mWidth] != 0) ? 1 : 0;
  30. int rightVal = (mValues[lastGeneration][((i + 1) + mWidth) % mWidth] != 0) ? 1 : 0;
  31.  
  32. unsigned int asStateComparison = 4 * leftVal
  33. + 1 * rightVal;
  34.  
  35. for (int j = 0; j < 5; ++j) {
  36. if (asStateComparison == j) {
  37. mValues[thisGeneration][i] = ((mRule & (1 << j)) != 0) ? 1 : 0;
  38. break;
  39. }
  40. }
  41. // Finally, print.
  42. }
  43. }
  44.  
  45. const unsigned int mRule;
  46. const unsigned int mWidth;
  47. int mGeneration;
  48. char* mValues[2];
  49. };
  50.  
  51. int main(int argc, char* argv[])
  52. {
  53. Automata1D test;
  54. test.evolve();
  55.  
  56. }
Success #stdin #stdout 0.01s 2852KB
stdin
Standard input is empty
stdout
Standard output is empty