Jump to content

One-dimensional cellular automata: Difference between revisions

Added C++
(Added C++)
Line 418:
_________________##_
</pre>
 
=={{header|C++}}==
Uses std::bitset for efficient packing of bit values.
<lang Cpp>#include <iostream>
#include <bitset>
#include <string>
 
const int ArraySize = 20;
const int NumGenerations = 10;
const std::string Initial = "0011101101010101001000";
 
int main()
{
// + 2 for the fixed ends of the array
std::bitset<ArraySize + 2> array(Initial);
 
for(int j = 0; j < NumGenerations; ++j)
{
std::bitset<ArraySize + 2> tmpArray(array);
for(int i = ArraySize; i >= 1 ; --i)
{
if(array[i])
std::cout << "#";
else
std::cout << "_";
int val = (int)array[i-1] << 2 | (int)array[i] << 1 | (int)array[i+1];
switch(val)
{
case 0: { tmpArray[i] = false; } break;
case 1: { tmpArray[i] = false; } break;
case 2: { tmpArray[i] = false; } break;
case 3: { tmpArray[i] = true; } break;
case 4: { tmpArray[i] = false; } break;
case 5: { tmpArray[i] = true; } break;
case 6: { tmpArray[i] = true; } break;
case 7: { tmpArray[i] = false; } break;
}
}
array = tmpArray;
std::cout << std::endl;
}
}</lang>
 
Output:
<pre>_###_##_#_#_#_#__#__
_#_#####_#_#_#______
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________</pre>
 
=={{header|Common Lisp}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.