[Question]
  [
There's a really important problem in cellular automata called the [Majority problem](https://en.wikipedia.org/wiki/Majority_problem_(cellular_automaton)):
> 
> The majority problem, or density classification task is the problem of finding one-dimensional cellular automaton rules that accurately perform majority voting.
> 
> 
> ...
> 
> 
> Given a configuration of a two-state cellular automata with i + j cells total, i of which are in the zero state and j of which are in the one state, a correct solution to the voting problem must eventually set all cells to zero if i > j and must eventually set all cells to one if i < j. The desired eventual state is unspecified if i = j.
> 
> 
> 
Although it has been proven that no cellular automata can solve the majority problem in all cases, there are many rules that can can solve it in the majority of cases. The Gacs-Kurdyumov-Levin automaton has an accuracy of about 78% with random initial conditions. The GKL rule isn't complicated:
* Radius of 3, meaning that the cell's new state depends on 7 previous cells: itself, the 3 cells to the right, and the 3 cells to the left.
* If a cell is currently `O`, its new state is the majority of itself, the cell to its left, and the cell 3 steps to its left.
* If a cell is currently `1`, its new state is the majority of itself, the cell to its right, and the cell 3 steps to its right.
Here is an example:
```
0 1 0 1 1 1 0 1 1 0 1 0 0 1
0 1 1 1 1 1 1 1 0 0 1 1 0 0
0 1 1 1 1 1 1 1 1 0 1 0 0 0
0 1 1 1 1 1 1 1 0 1 0 1 0 0
0 1 1 1 1 1 1 0 1 0 1 0 1 0
0 1 1 1 1 1 0 1 0 1 0 1 1 1
1 1 1 1 1 0 1 0 1 1 1 1 1 1
1 1 1 1 0 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1
```
In this example, the cellular automaton correctly calculated that 8 > 6. Other examples take longer periods of time, and produce some cool patterns in the meantime. Below are two examples I randomly found.
```
0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 1 1 0 1 1 1 1 0 1 0 0 1 1 1
1 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 1 0 0 0 1 0 0 1 1
```
---
## Taking it to the next level
As far as my internet research has shown, almost all academic research on the majority problem has been conducted with 2-state CAs. In this challenge, we are going to expand the majority problem to **3-state CAs**. I will call this the *plurality problem*. [Plurality](https://en.wikipedia.org/wiki/Plurality_%28voting%29), or relative majority, refers to the condition in which one of the options has more votes than each of the alternatives, but not necessarily a majority of all votes.
**Problem Statement**
1. There is a 3-state 1D cellular automaton with radius 3.
2. There are **151** cells with a circular boundary condition.
3. These cells are given a random starting state, on the sole condition that 1 of the 3 states has a strict plurality. "Random" means an independent uniform distribution for each cell.
4. The accuracy of a rule is the percentage of (valid) random initial conditions in which all of the cells synchronize to the correct state (the one with plurality) **within 10000 generations**.
5. The goal is to find a rule with high accuracy,
Plurality edge cases: Any configuration with 50/50/51 is a valid starting configuration (since there is a strict plurality), while any configuration with 51/51/49 is not valid (since there is not a strict plurality).
The search space is 3^3^7 (~3e1043), far outside the reach of any exhaustive search. This means that you will need to make use of other techniques, like genetic algorithms, in order to solve this problem. It will also take some human engineering.
The 10000 generation rule is subject to change, depending on the runtimes/accuracy of the rules people find. If it is too low to allow reasonable rates of convergence, then I can raise it. Alternatively, I can lower it to serve as a tie-breaker.
## Winning
The winner is the person who submits the radius-3 CA rule with the highest accuracy out of all of the contestants.
Your submission should include...
* A description of the rule (using [Wolfram code](https://en.wikipedia.org/wiki/Wolfram_code) if necessary)
* The accuracy rate and sample size
* A reasonably-sized *explanation* of how you discovered the rule, including programs you wrote to solve it, or any "manual" engineering. (This being the most interesting part, since everything else is just raw numbers.)
## Prior Work
* A paper by [Juille and Pollack](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.67.6665&rep=rep1&type=pdf), describing how they evolved a 2-state rule with 86% accuracy.
* [This paper](http://web.cecs.pdx.edu/%7Emm/EGSCA.pdf) used r=3, 149-cell, 2-state CAs. It did not attempt to the solve the majority problem, however, but instead to find rules that quickly resulting in an alternating all-`1`-all-`0` pattern. Despite these differences, I suspect many techniques will be similar.
* A (not very helpful because it's behind a paywall) paper by [Wolz and de Oliviera](http://www.oldcitypublishing.com/journals/jca-home/jca-issue-contents/jca-volume-3-number-4-2008/jca-3-4-p-289-312/) which currently hold the 2-state record
  
[Answer]
# Sort of GKL plus hill climbing, 61.498%
* If a cell is a 0, look at the cells 3 to the left, 1 to the left and at itself. Set value to majority. If it's a tie, stay the way you are.
* If a cell is a 1, look at the cells 3 to the right, 1 to the right and at itself. Set value to majority. If it's a tie, stay the way you are.
* If a cell is a 2, look at the cells 2 to the left, 2 to the right and 3 to the right. Set value to majority. If it's a tie, stay the way you are.
I got 59453 right out of 100000 total, 59.453%
Some mutating and hill-climbing resulted in 61498/100000 = 61.498%.
I'll probably test a bit more and will post some more information later.
[Answer]
# "Just toss out the 2s and do GKL" -- 55.7%
It's not so easy to guess what a good rule would be, so I tried to at least come up with something that would score above 1/3. The strategy is to try to get the right answer when the majority state is 0 or 1, and accept the loss if it's 2. It scored 56.5% over 100,000 trials, which is somehow slightly better than what would be expected from multiplying 78% (score of GKL) \* 2/3 (fraction of the time when answer is 0 or 1) = 52%.
More concretely, the strategy is as follows:
* If the cell is 0 or 1, take the majority of the 3 cells as in the GKL strategy, but ignoring any neighbors that are 2. If it's a tie, leave the cell unchanged.
* If the cell is 2, choose whichever is more numerous of 0 or 1 in the entire neighborhood. If it's a tie, choose the leftmost value that is 0 or 1. If all the neighbors are 2, stay 2.
I used this code to test:
```
#include <iostream>
#include <algorithm>
#include <string.h>
#include <random>
#include <cassert>
#define W 151
#define S 3
#define R 3
typedef int state;
struct tape {
    state s[R+W+R];
    state& operator[](int i) {
        return s[i + R];
    }
    template<typename Rule> void step(Rule r) {
        for(int i = 0; i < R; i++) s[i] = s[W + i];
        for(int i = 0; i < R; i++) s[R + W + i] = s[R + i];
        for(int i = 0; i < W; i++) {
            s[i] = r(s + R + i);
        }
        memmove(s + R, s, W * sizeof(*s));
    }
    state unanimous() {
        state st = (*this)[0];
        for(int i = 1; i < W; i++) {
            if((*this)[i] != st)
                return -1;
        }
        return st;
    }
};
std::ostream& operator<<(std::ostream& s, tape& t) {
    for (int i = 0; i < W; i++)
        s << t[i];
    return s;
}
state randomize(tape& t) {
    static std::mt19937 rg(390332);
    begin:
    int c[S]{};
    for(int i = 0; i < W; i++) {
        state s = rg() % S;
        c[s]++;
        t[i] = s;
    }
    state* smax = std::max_element(c, c + R);
    int nmaj = 0;
    for (int n : c) nmaj += n == *smax;
    if (nmaj > 1) goto begin;
    return smax - c;
}
template<bool PrintSteps, typename Rule> int simulate(Rule r, int trials, int giveup) {
    int successes = 0;
    for(state s = 0; s < S; s++) {
        state t[2 * R + 1];
        for(int i = 0; i <= 2 * R; i++) t[i] = s;
        assert(r(t + R) == s);
    }
    while(trials--) {
        tape tp;
        state desired = randomize(tp);
        int steps = giveup;
        while(steps--) {
            tp.step(r);
            state u = tp.unanimous();
            if(~u) {
                bool correct = u == desired;
                if(PrintSteps) {
                    std::cout << correct << ' ' << giveup - steps << '\n';
                }
                successes += correct;
                break;
            }
        }
    }
    return successes;
}
struct ixList {
    int n;
    int i[2 * R + 1];
};
state rule_justTossOutThe2sAndDoGKL(const state* t) {
    const ixList ixl[] = {
        { 3,{ -3, -1, 0 } },
        { 3,{ 0, 1, 3 } },
        { 6,{ -3, -2, -1, 1, 2, 3 } } 
    };
    int c[S]{};
    for (int i = 0; i < ixl[*t].n; i++)
        c[t[ixl[*t].i[i]]]++;
    if (c[0] > c[1]) return 0;
    if (c[1] > c[0]) return 1;
    if (*t < 2) return *t;
    for (int i = -R; i <= R; i++)
        if (t[i] < 2) return t[i];
    return 2;
}
int main()
{
    int nt = 100000;
    int ns = simulate<false>(rule_justTossOutThe2sAndDoGKL, nt, 10000);
    std::cout << (double)ns / nt << '\n';
    return 0;
}
```
[Answer]
# "Just steal whatever's best and evolve it", bleh
Edit: in its current state this answer, rather than finding better patterns, finds a better random sample.
This answer encodes/decodes solutions by enumerating all states as ternary numbers (least-significant digit first). The solution for 59.2%:
```
000000000010010010000000000000000000000000000000000000000000010000010000110000000
000000000010010010000000000111111101111111111111111111000011000010011011000011010
000000000012010011001000000021111111111120111211111111000000000000011010000010000
000011000010022110000000202000000002000000000020000000001010000000011011000011010
020000000010010010001000000111101111111111111111111111010011000011111111010011010
000000000010010010000000000111111111101111111111112111000011010110111011010011011
000000000010010010000000000010000000000000000100002011000000000100011010020010000
000020020010010010000200000111102111111111111111111101000011010010111011000011011
000100000010010010000000000121111111111111111111111111000210000012011011002011010
000000000010010110000000000111112112111111111001111111000010000010011011000011010
000000000010010120000200000111211111111111111111110111110011010011100111010011011
000000000010010010000000000011111111111111111111111111000011010010111211210012020
010000000010010010020100020111110111111111111111111110010111010011011111010111011
002000000010010010000000000111110111111111211111111111001111111111111111111111111
000000000110010010000000000111111111111111211111111111010111011111111111011111011
001000000010010010000000000011111101111111111111110111000011010010111011010011010
001000000010010110000000000111111111111111102111110111010111011111111111011111101
000000000210010010000000000111111111111111111111011111010011010011111111010111011
000000000010010010000000000112111111111111111111101011000000000000011010000010000
000000000010010010000000000111111111111111111111111111000011010010111011010011011
000200000012010010000000000111111111111112111111111111000010000210011211001011010
000000000010010211000002000111111111111111111111111111000001010010111011010011010
000021200010210010000101100111111111111211111110110211010111021111111101010111111
000000000010010010000000000111111111111101111111111111010011010111111111010110021
000200000010010010000000010111111111101111111121112111000210001010011011000011010
000000000010010010000000000111111111111111111111111111210011010021111111010111011
000020000010010010000000000111111111111111111111111111000011010010121011010011012
```
This answer was evolved from feersum's 55.7%, using the following code. This code requires [libop](https://github.com/orlp/libop), which is my personal C++ header-only library. It's very easy to install, just do `git clone https://github.com/orlp/libop` in the same directory as where you've saved the program. I suggest compiling with `g++ -O2 -m64 -march=native -std=c++11 -g`. For speedy development I also suggest precompiling libop by running the above command on `libop/op.h`.
```
#include <cstdint>
#include <algorithm>
#include <iostream>
#include <cassert>
#include <random>
#include "libop/op.h"
constexpr int MAX_GENERATIONS = 500;
constexpr int NUM_CELLS = 151;
std::mt19937_64 rng;
double worst_best_fitness;
// We use a system with okay-ish memory density. We represent the ternary as a
// 2-bit integer. This means we have 32 ternaries in a uint64_t.
//
// There are 3^7 possible states, requiring 4374 bits. We store this using 69
// uint64_ts, or little over half a kilobyte.
// Turn 7 cells into a state index, by encoding as ternary.
int state_index(const int* cells) {
    int idx = 0;
    for (int i = 0; i < 7; ++i) {
        idx *= 3;
        idx += cells[6-i];
    }
    return idx;
}
// Get/set a ternary by index from a 2-bit-per-ternary encoded uint64_t array.
int get_ternary(const uint64_t* a, size_t idx) {
    return (a[idx/32] >> (2*(idx % 32))) & 0x3;
}
void set_ternary(uint64_t* a, size_t idx, int val) {
    assert(val < 3);
    int shift = 2*(idx % 32);
    uint64_t shifted_val = uint64_t(val) << shift;
    uint64_t shifted_mask = ~(uint64_t(0x3) << shift);
    a[idx/32] = (a[idx/32] & shifted_mask) | shifted_val;
}
struct Rule {
    uint64_t data[69];
    double cached_fitness;
    Rule(const char* init) {
        cached_fitness = -1;
        for (auto i : op::range(69)) data[i] = 0;
        for (auto i : op::range(2187)) set_ternary(data, i, init[i] - '0');
    }
    double fitness(int num_tests = 1000);
    Rule* random_mutation(int num_mutate) const {
        auto new_rule = new Rule(*this);
        auto r = op::range(2187);
        std::vector<int> indices;
        op::random_sample(r.begin(), r.end(),
                          std::back_inserter(indices), num_mutate, rng);
        for (auto idx : indices) {
            set_ternary(new_rule->data, idx, op::randint(0, 2, rng));
        }
        new_rule->cached_fitness = -1;
        return new_rule;
    }
    int new_state(const int* cells) const {
        return get_ternary(data, state_index(cells));
    }
    void print_rule() const {
        for (auto i : op::range(2187)) {
            std::cout << get_ternary(data, i);
            if (i % 81 == 80) std::cout << "\n";
        }
    }
};
struct Automaton {
    uint64_t state[5];
    int plurality, generation;
    Automaton() : generation(0) {
        for (auto i : op::range(5)) state[i] = 0;
        int strict = 0;
        while (strict != 1) {
            int votes[3] = {};
            for (auto i : op::range(NUM_CELLS)) {
                int vote = op::randint(0, 2, rng);
                set_ternary(state, i, vote);
                votes[vote]++;
            }
            // Ensure strict plurality.
            plurality = std::max_element(votes, votes + 3) - votes;
            strict = 0;
            for (auto i : op::range(3)) strict += (votes[i] == votes[plurality]);
        }
    }
    void print_state() {
        for (int i = 0; i < 151; ++i) std::cout << get_ternary(state, i);
        std::cout << "\n";
    }
    bool concensus_reached() {
        int target = get_ternary(state, 0);
        for (auto i : op::range(NUM_CELLS)) {
            if (get_ternary(state, i) != target) return false;
        }
        return true;
    }
    void next_state(const Rule& rule) {
        uint64_t new_state[5] = {};
        std::vector<int> cells;
        for (auto r : op::range(-3, 4)) {
            cells.push_back(get_ternary(state, (r + NUM_CELLS) % NUM_CELLS));
        }
        for (auto i : op::range(NUM_CELLS)) {
            set_ternary(new_state, i, rule.new_state(cells.data()));
            cells.erase(cells.begin());
            cells.push_back(get_ternary(state, (i + 4) % NUM_CELLS));
        }
        for (auto i : op::range(5)) state[i] = new_state[i];
        generation++;
    }
};
double Rule::fitness(int num_tests) {
    if (cached_fitness == -1) {
        cached_fitness = 0;
        int num_two = 0;
        for (auto test : op::range(num_tests)) {
            Automaton a;
            while (a.generation < MAX_GENERATIONS && !a.concensus_reached()) {
                a.next_state(*this);
            }
            if (a.generation < MAX_GENERATIONS &&
                get_ternary(a.state, 0) == a.plurality &&
                a.plurality == 2) num_two++;
            cached_fitness += (a.generation < MAX_GENERATIONS &&
                               get_ternary(a.state, 0) == a.plurality);
            if (cached_fitness + (num_tests - test) < worst_best_fitness) break;
        }
        if (num_two) std::cout << cached_fitness << " " << num_two << "\n";
        cached_fitness;
    }
    return cached_fitness;
}
int main(int argc, char** argv) {
    std::random_device rd;
    rng.seed(42); // Seed with rd for non-determinism.
    const char* base = 
        "000000000010010010000000000000000000000000000000000000000000000000010000000000000"
        "000000000010010010000000000111111111111111111111111111000010000010011011000011010"
        "000000000010010010000000000111111111111111111111111111000000000000011010000010000"
        "000000000010010010000000000000000000000000000000000000000010000010011011000011010"
        "000000000010010010000000000111111111111111111111111111010011010011111111010111011"
        "000000000010010010000000000111111111111111111111111111000011010010111011010011011"
        "000000000010010010000000000000000000000000000000000000000000000000011010000010000"
        "000000000010010010000000000111111111111111111111111111000011010010111011010011011"
        "000000000010010010000000000111111111111111111111111111000010000010011011000011010"
        "000000000010010010000000000111111111111111111111111111000010000010011011000011010"
        "000000000010010010000000000111111111111111111111111111010011010011111111010111011"
        "000000000010010010000000000111111111111111111111111111000011010010111011010011010"
        "000000000010010010000000000111111111111111111111111111010011010011111111010111011"
        "000000000010010010000000000111111111111111111111111111011111111111111111111111111"
        "000000000010010010000000000111111111111111111111111111010111011111111111011111111"
        "000000000010010010000000000111111111111111111111111111000011010010111011010011010"
        "000000000010010010000000000111111111111111111111111111010111011111111111011111111"
        "000000000010010010000000000111111111111111111111111111010011010011111111010111011"
        "000000000010010010000000000111111111111111111111111111000000000000011010000010000"
        "000000000010010010000000000111111111111111111111111111000011010010111011010011011"
        "000000000010010010000000000111111111111111111111111111000010000010011011000011010"
        "000000000010010010000000000111111111111111111111111111000011010010111011010011010"
        "000000000010010010000000000111111111111111111111111111010111011111111111011111111"
        "000000000010010010000000000111111111111111111111111111010011010011111111010111011"
        "000000000010010010000000000111111111111111111111111111000010000010011011000011010"
        "000000000010010010000000000111111111111111111111111111010011010011111111010111011"
        "000000000010010010000000000111111111111111111111111111000011010010111011010011012"
    ;
    // Simple best-only.
    std::vector<std::unique_ptr<Rule>> best_rules;
    best_rules.emplace_back(new Rule(base));
    worst_best_fitness = best_rules.back()->fitness();
    while (true) {
        const auto& base = *op::random_choice(best_rules.begin(), best_rules.end(), rng);
        std::unique_ptr<Rule> contender(base->random_mutation(op::randint(0, 100, rng)));
        // Sort most fit ones to the beginning.
        auto most_fit = [](const std::unique_ptr<Rule>& a, const std::unique_ptr<Rule>& b) {
            return a->fitness() > b->fitness();
        };
        if (contender->fitness() >= best_rules.back()->fitness()) {
            std::cout << contender->fitness();
            double contender_fitness = contender->fitness();
            best_rules.emplace_back(std::move(contender));
            std::sort(best_rules.begin(), best_rules.end(), most_fit);
            if (best_rules.size() > 5) best_rules.pop_back();
            std::cout << " / " << best_rules[0]->fitness() << "\n";
            worst_best_fitness = best_rules.back()->fitness();
            if (contender_fitness == best_rules.front()->fitness()) {
                best_rules.front()->print_rule();
            }
        }
    }
    return 0;
}
```
[Answer]
# Hand Coded, 57.541%
This actually only looks at the 5 cells above it. It could probably be improved by increasing the range it looks at. Ran with 100,000 test cases.
Algorithm:
```
If above == 0:
   if to the left there are only 2s or there is a 1 separated by 2s
       next state = 2
   else
       next state = 0
If above == 1:
   if to the right there are only 2s or there is a 0 separated by 2s
       next state = 2
   else
       next state = 1
If above == 2:
   ignore 0s to the left if the 0 is left of a 1 on the left
   ignore 1s to the right if the 1 is right of a 0 on the right
   if the closest 0 on the left is closer than the closest 1 on the right
       next state = 0
   else if the closest 1 on the right is closer than the closest 0 on the left
       next state = 1
   else
       next state = 2
```
Gene:
```
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222222222222
000000000222222222000222222111111111111111111111111111222111111111111111111111111
000000000222222222000222222111111111111111111111111111000000000111111111222111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222222222222
000000000222222222000222222111111111111111111111111111222111111111111111111111111
000000000222222222000222222111111111111111111111111111000000000111111111222111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222222222222222222222222222222000000000222222222222222222
000000000222222222000222222111111111111111111111111111222111111111111111111111111
000000000222222222000222222111111111111111111111111111000000000111111111222111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
000000000222222222000222222111111111111111111111111111000222222111111111111111111
000000000222222222000222222222222222222222222222222222000000000222222222000222222
```
Testing code:
```
import java.lang.Math.*
import java.util.*
const val RADIUS = 3;
const val STATES = 3;
const val DIAMETER = 2 * RADIUS + 1
const val TAPE_LENGTH = 151
val CODE_SIZE = pow(STATES.toDouble(), DIAMETER.toDouble()).toInt()
const val GRADE_RUNS = 100000
const val GRADE_MAX_TIME = 10000
operator fun IntArray.inc() : IntArray {
    val next = this.clone()
    var i = 0
    while (i < size) {
        if (this[i] == STATES - 1) {
            next[i] = 0
        } else {
            next[i]++
            break
        }
        i++
    }
    return next
}
val IntArray.index : Int
    get() {
        var total = 0
        for (i in (size - 1) downTo 0) {
            total *= STATES
            total += this[i]
        }
        return total
    }
interface IRule {
    operator fun get(states : IntArray) : Int
}
fun IntArray.equalsArray(other: IntArray) = Arrays.equals(this, other)
class Rule : IRule {
    constructor(rule : IRule) {
        val start = IntArray(DIAMETER)
        var current = start.clone()
        code = IntArray(CODE_SIZE)
        try {
            do {
                code[current.index] = rule[current]
                current++
            } while (!current.equalsArray(start));
        } catch (e : Throwable) {
            println(Arrays.toString(code))
            println(Arrays.toString(current))
            throw e
        }
    }
    constructor(code : IntArray) {
        this.code = IntArray(CODE_SIZE) { if (it < code.size) code[it] else 0 }
    }
    val code : IntArray
    override fun get(states: IntArray) : Int {
        return code[states.index]
    }
    override fun toString() : String {
        val b = StringBuilder()
        for (i in 0 until CODE_SIZE) {
            if (i > 0 && i % pow(STATES.toDouble(), RADIUS.toDouble() + 1).toInt() == 0) {
                b.append('\n')
            }
            b.append(code[i])
        }
        return b.toString()
    }
    fun grade() : Double {
        var succeeded = 0
        for (i in 0 until GRADE_RUNS) {
            if (i % (GRADE_RUNS / 100) == 0) {
                println("${i/(GRADE_RUNS / 100)}% done grading.")
            }
            var tape : Tape
            do {
                tape = Tape()
            } while (tape.majority() == -1);
            val majority = tape.majority()
            val beginning = tape
            var j = 0
            while (j < GRADE_MAX_TIME && !tape.allTheSame()) {
                tape = tape.step(this)
                j++
            }
            if (tape.stabilized(this) && tape.majority() == majority) {
                succeeded++
            }/* else if (beginning.majority() != 2) {
                println(beginning.majority())
                tape = beginning
                for (j in 1..100) {
                    println(tape)
                    tape = tape.step(this)
                }
                println(tape)
            }*/
        }
        return succeeded.toDouble() / GRADE_RUNS
    }
}
fun getRandomState() : Int {
    return (random() * STATES).toInt()
}
class Tape(val tape : IntArray) {
    constructor() : this(IntArray(TAPE_LENGTH) { getRandomState() } )
    fun majority() : Int {
        val totals = IntArray(STATES)
        for (cell in tape) {
            totals[cell]++
        }
        var best = -1
        var bestScore = -1
        for (i in 0 until STATES) {
            if (totals[i] > bestScore) {
                best = i
                bestScore = totals[i]
            } else if (totals[i] == bestScore) {
                best = -1
            }
        }
        return best
    }
    fun allTheSame() : Boolean {
        for (i in 1 until TAPE_LENGTH) {
            if (this[i] != this[0]) {
                return false
            }
        }
        return true
    }
    operator fun get(index: Int) = tape[((index % TAPE_LENGTH) + TAPE_LENGTH) % TAPE_LENGTH]
    fun step(rule : IRule) : Tape {
        val nextTape = IntArray ( TAPE_LENGTH )
        for (i in 0 until TAPE_LENGTH) {
            nextTape[i] = rule[IntArray(DIAMETER) { this[i + it - RADIUS] }]
        }
        return Tape(nextTape)
    }
    fun stabilized(rule : IRule) = allTheSame() && majority() == step(rule).majority()
    override fun toString() : String {
        val b = StringBuilder()
        for (cell in tape) {
            b.append(cell)
        }
        return b.toString()
    }
}
fun main(args : Array<String>) {
    val myRule = Rule(object : IRule {
        override fun get(states: IntArray): Int {
            if (states[3] == 0) {
                if (states[2] == 1) {
                    return 2
                } else if (states[2] == 0) {
                    return 0
                } else if (states[1] == 1) {
                    return 2
                } else if (states[1] == 0) {
                    return 0
                } else {
                    return 2
                }
            } else if (states[3] == 1) {
                if (states[4] == 0) {
                    return 2
                } else if (states[4] == 1) {
                    return 1
                } else if (states[5] == 0) {
                    return 2
                } else if (states[5] == 1) {
                    return 1
                } else {
                    return 2
                }
            } else {
                if (states[2] == 0) {
                    if (states[4] != 1) {
                        return 0
                    }
                } else if (states[4] == 1) {
                    return 1
                }
                if (states[1] == 0 && states[2] != 1) {
                    if (states[5] != 1) {
                        return 0
                    }
                } else if (states[5] == 1 && states[4] != 0) {
                    return 1
                }
                return 2
            }
        }
    })
    var tape = Tape()
    println(myRule.grade())
}
```
[Example](http://pastebin.com/raw/kTn8pLZb)
]